[英]autotagging aws instance with boto3
我正在尝试检索 iam 用户 email 和启动实例并使用它来标记实例的帐户 ID,帐户 ID 运行良好但用户 email 返回错误 lamnbda function 由返回实例的 cloudwatch 事件规则触发当实例 state 更改为正在运行时,id 为 lambda function
import boto3
def lambda_handler(event, context):
print(event)
# Get the EC2 instance ID from the event data
instance_id = event['detail']['instance-id']
# Get the account ID
sts_client = boto3.client('sts')
identity = sts_client.get_caller_identity()
account_id = identity['Account']
# Tag the EC2 instance with the email and account ID
ec2 = boto3.client('ec2')
# Describe the instance to get the IAM role ARN
response = ec2.describe_instances(InstanceIds=[instance_id])
iam_role_arn = response['Reservations'][0]['Instances'][0]['IamInstanceProfile']['Arn']
# Get the IAM client
iam = boto3.client('iam')
# Get the role name from the IAM role ARN
role_name = iam_role_arn.split('/')[1]
# Get the role details
role_details = iam.get_role(RoleName=role_name)
# Get the policy ARN from the role details
policy_arn = role_details['Role']['AssumeRolePolicyDocument']['Statement'][0]['Principal']['AWS'][0]
# Get the policy details
policy_details = iam.get_policy(PolicyArn=policy_arn)
# Get the user ARN from the policy details
user_arn = policy_details['Policy']['UserName']
# Get the user details
user_response = iam.get_user(UserName=user_arn)
# Get the user email from the user details
user_email = user_response['User']['UserName']
ec2.create_tags(
Resources=[instance_id],
Tags=[
{
'Key': 'Email',
'Value': email
},
{
'Key': 'AccountID',
'Value': user_email
}
]
)
您应该已经拥有启动该实例的用户的访问密钥,以便您可以使用GetAccessKeyLastUsed反向查找关联的 IAM 用户,在 boto3 中作为get_access_key_last_used可用,并检索 IAM 用户的名称(严格来说不是 email 地址)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.