boto3如何从实例中检索弹性ip [英] boto3 how to retrieve the elastic ip from an instance
问题描述
我需要执行以下操作:
我有一些包含特定标签的实例,我需要遍历这些实例,对于包含该特定标签的每个实例,如果该实例附加了弹性ip,则需要使用相同的标签来标记该弹性ip..我的代码如下:
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.
推荐答案
您可以在 boto3.resource('ec2')
资源 vpc_addresses
上访问VPC或经典弹性IP.>和 classic_addresses
.
You may access VPC or classic Elastic IPs on the boto3.resource('ec2')
resources vpc_addresses
and classic_addresses
respectively.
如果地址已关联,则它们将具有 instance_id
属性.您将可以使用 ec2.Instance(address.instance_id).tags
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
如果要遍历所有地址,则 boto3.client('ec2')
客户端具有 describe_addresses
,该信息将为您提供相同的信息.
If you want to go through all addresses, the boto3.client('ec2')
client has describe_addresses
that will give you the same information.
这篇关于boto3如何从实例中检索弹性ip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!