boto3 how to retrieve the elastic ip from an instance

北战南征 提交于 2021-01-28 16:33:21

问题


I need to do the following:

I have some instances that contain a certain tag, I need to loop through those instances and for each instance which contains that certain tag, if that instance has an elastic ip attached, I need to tag that elastic ip with that same tag. My code is the following:

import boto3
import json

region_list = ['us-east-1']
session = boto3.Session(profile_name='default')

for region in region_list:
    ec2 = session.resource('ec2',region)
    client = boto3.client('ec2',region)
    # Retrieve instances that contain this specific tag
    instances = ec2.instances.filter(Filters=[{'Name':'tag:MyTargetTag', 'Values':['*']}])

    for instance in instances:
        for tag in instance.tags:
            if tag['Key'] == "MyTargetTag":
                MyTargetTag = tag['Value']
        ## check if this instance has an elasticip
        ## if it has, assign the value of MyTargetTag to it
        response = client.add_tags(
            ResourceArns=[
                #elasticip ip identifier of some sort,
            ],
            Tags=[
                {
                    'Key': 'MyTargetTag',
                    'Value': MyTargetTag
                },
            ]
        )

I've read through the docs and videos and what not but honestly I don't understand it quite completely and I'm just doing trial and error without any success.


回答1:


You may access VPC or classic Elastic IPs on the boto3.resource('ec2') resources vpc_addresses and classic_addresses respectively.

If the addresses are associated, they will have an instance_id attribute. You'll be able to get the tags with ec2.Instance(address.instance_id).tags

If you want to go through all addresses, the boto3.client('ec2') client has describe_addresses that will give you the same information.




回答2:


ElasticIP addresses are 'associated' with a network interface. One instance may have multiple network interfaces, each of which may or may not have an Elastic IP address assigned to it.

This lists all the ElasticIPs attached to any of your instances, for example:

import boto3 
from pprint import pprint

ec2 = boto3.resource('ec2')

instances = ec2.instances.filter()
for instance in instances:
    for interface in instance.network_interfaces:
        if interface.association_attribute is not None:
            pprint (interface.association_attribute)

However I can't see any functionality in boto3 that allows you to return the ElasticIP as an object, or apply any tags to it. It's clearly possible, as you can do it via the console, I just can't see the functionality in boto3.



来源:https://stackoverflow.com/questions/53215469/boto3-how-to-retrieve-the-elastic-ip-from-an-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!