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

时间:2018-04-25 00:02:40

标签: python amazon-web-services amazon-ec2 boto boto3

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

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

1 个答案:

答案 0 :(得分:2)

我认为您可以使用ECS API执行此操作。 E.g。

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)