Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- import time
- import boto3
- import os
- ec2 = boto3.client("ec2")
- iam = boto3.client("iam")
- Ec2Instance = boto3.resource("ec2").Instance
- def get_ec2_instance(instance_id):
- return Ec2Instance(instance_id)
- def acquire_instance_profile(profile_name):
- profile = iam.get_instance_profile(InstanceProfileName=profile_name)["InstanceProfile"]
- return profile
- def lambda_handler(event, context):
- instance = get_ec2_instance(event['detail']['resourceId'])
- if instance.iam_instance_profile is None:
- profile_name = os.environ['default_role']
- profile = acquire_instance_profile(profile_name)
- ec2.associate_iam_instance_profile(
- IamInstanceProfile={
- 'Arn': profile['Arn'],
- 'Name': profile_name
- },
- InstanceId=event['detail']['resourceId']
- )
- return {
- "InstanceProfileName": profile_name, # No need for lexical-xform, the profile took the name we specified
- "InstanceProfileArn": profile["Arn"],
- "ActionTaken": "Assigned InstanceProfile \"{}\" to the Instance (it lacked a profile).".format(profile_name)
- }
- else:
- policy_arns = [ "arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM",
- "arn:aws:iam::257796259288:policy/calibre-webS3"
- ]
- role_name = iam.get_instance_profile(InstanceProfileName=instance.iam_instance_profile['Arn'].rsplit('/',1)[1])['InstanceProfile']['Roles'][0]['RoleName']
- attached_policies = iam.list_attached_role_policies(RoleName=role_name)
- print(attached_policies)
- attached_policy_arns =[]
- for i in range(len(attached_policies['AttachedPolicies'])):
- attached_policy_arns.append(attached_policies['AttachedPolicies'][i]['PolicyArn'])
- print(attached_policy_arns)
- for policy in policy_arns:
- if policy not in attached_policy_arns:
- iam.attach_role_policy(RoleName=role_name, PolicyArn=policy)
- print(policy + "was attached.")
- return {
- 'statusCode': 200,
- 'body': json.dumps('Hello from Lambda!')
- }
Advertisement
Add Comment
Please, Sign In to add comment