Skip to main content
 首页 » 编程设计

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

2024年09月07日8fff_TT

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

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

请您参考如下方法:

我认为您可以使用 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)