简体   繁体   中英

autotagging aws instance with boto3

i am trying to retrieve the iam user email and account id who started an instance and use it to tag the instance, the account id works well but the user email return an error the lamnbda function was trigger by a cloudwatch event rule that returns the instance id to the lambda function when the instance state change to running

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
          }
      ]
  )

You should already have the access key for the user that launched the instance so you can reverse lookup the associated IAM user using GetAccessKeyLastUsed , available in boto3 as get_access_key_last_used and retrieve the IAM user's name (which is not strictly an email address).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM