如何使用python获取ECS集群内实例的ip地址?

时间:2018-11-18 18:06:09

标签: python amazon-web-services boto3

导入boto3

client = boto3.client('ecs')

响应= client.list_clusters()

response1 = client.list_container_instances(     cluster ='Cluster1234', )

print(response,response1)

1 个答案:

答案 0 :(得分:0)

来自list_container_instances的响应为您提供了containerInstanceArns中的容器实例ARN的列表。

然后您可以将其作为containerInstances传递给describe_container_instances,以在containerInstances[*].ec2InstanceId中获得容器实例及其基础EC2实例ID的列表。

然后您可以将这些EC2实例ID作为InstanceIds传递给describe_instances,这将给您提供IP地址。

也许有一种更简洁的方法,但是我还没有立即意识到。

这是一个例子:

import boto3

ecs = boto3.client('ecs', region_name='us-east-1')
ec2 = boto3.client('ec2', region_name='us-east-1')

rc = ecs.list_clusters()

for cluster in rc['clusterArns']:
    ci = ecs.list_container_instances(cluster=cluster)

    if len(ci['containerInstanceArns']) > 0:
        r2 = ecs.describe_container_instances(
            cluster=cluster,
            containerInstances=ci['containerInstanceArns'])

        ids = [x['ec2InstanceId'] for x in r2['containerInstances']]

        r3 = ec2.describe_instances(InstanceIds=ids)

        for r in r3['Reservations']:
            for i in r['Instances']:
                print("{0}: instance {1}, state {2}, AMI {3}, private IP {4}, public IP {5}".format(
                    cluster.split('/')[-1],
                    i['InstanceId'],
                    i['State']['Name'],
                    i['ImageId'],
                    i['PrivateIpAddress'] if 'PrivateIpAddress' in i else 'n/a',
                    i['PublicIpAddress'] if 'PublicIpAddress' in i else 'n/a'))

这将产生如下输出:

cluster-101: instance i-01234e5ea85f30ba7, state running, AMI ami-045f1b3f87ed83659, private IP 10.0.0.222, public IP 54.166.303.1
cluster-101: instance i-023452ab72c755e01, state running, AMI ami-045f1b3f87ed83659, private IP 10.0.1.333, public IP 54.166.202.2
cluster-101: instance i-03456645cc5d9b19d, state running, AMI ami-045f1b3f87ed83659, private IP 10.0.1.444, public IP 54.166.101.3