AWS 资源管理与日志管理实践
1. 从 Python 脚本中检索 EC2 标签
在 AWS 环境中,我们可以使用 Python 脚本从 EC2 实例中检索标签。以下是一个示例代码:
from boto.utils import get_instance_metadata
from boto.ec2 import connect_to_region
metadata = get_instance_metadata()
my_instance_id = metadata['instance-id']
conn = connect_to_region('us-east-1')
for reservations in conn.get_all_instances(filters={'instance-id': my_instance_id}):
# There will be only one instance in the results
for instance in reservations.instances:
for tag in instance.tags:
# Iterate through the tags, printing the keys and values
print "Key \'%s\' has value \'%s\'" % (tag, instance.tags[tag])
这个脚本不会嵌入任何 IAM 凭证,它假设运行该脚本的实例已分配了 IAM 角色。Boto 会在可用时自动使用 IAM