如何在Python AWS boto API中获取EC2实例ID的容器实例列表

问题描述 投票:2回答:1

我一直在Python的boto3客户端(http://boto3.readthedocs.io/en/latest/reference/services/ec2.html)中搜索EC2 api。给定EC2实例ID,我希望能够找到在属于特定ECS集群ID的EC2实例上运行的所有容器实例。我似乎无法找到任何执行此操作的API调用。我怎样才能获得这些信息?

我想要这个信息,因为给定EC2实例ID我想知道所有容器和在这些容器上运行的所有任务。

python amazon-web-services amazon-ec2 boto boto3
1个回答
2
投票

我认为您可以使用ECS API执行此操作。例如。

import boto3

CLUSTER = 'YOUR_CLUSTER_ID'
EC2 = 'YOUR_EC2_ID'

ecs = boto3.client('ecs')

ci_list_response = ecs.list_container_instances(
    cluster=CLUSTER
)

# Describe those ARNs
ci_descriptions_response = ecs.describe_container_instances(
    cluster=CLUSTER,
    containerInstances=ci_list_response['containerInstanceArns']
)

# Look for a container instance with the given EC2 instance ID
# Then for want of something better to do, print all the details
for ci in ci_descriptions_response['containerInstances']:
    if ci['ec2InstanceId'] == EC2:
        print(ci)

编辑:在我看来,您可能对该实例上正在运行的任务更感兴趣,您也可以获得该任务。

import boto3

CLUSTER = 'YOUR_CLUSTER_ID'
EC2 = 'YOUR_EC2_ID'

ecs = boto3.client('ecs')

ci_list_response = ecs.list_container_instances(
    cluster=CLUSTER
)

# Describe those ARNs
ci_descriptions_response = ecs.describe_container_instances(
    cluster=CLUSTER,
    containerInstances=ci_list_response['containerInstanceArns']
)

# Look for a container instance with the given EC2 instance ID
# Then for want of something better to do, print all the details
for ci in ci_descriptions_response['containerInstances']:
    if ci['ec2InstanceId'] == EC2:

        # List tasks on this container instance
        t_list_response = ecs.list_tasks(
            cluster=CLUSTER,
            containerInstance=ci['containerInstanceArn']
        )

        # Describe tasks
        t_descriptions_response = ecs.describe_tasks(
            cluster=CLUSTER,
            tasks=t_list_response['taskArns']
        )

        print(t_descriptions_response)
© www.soinside.com 2019 - 2024. All rights reserved.