Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. import json
  2. import time
  3. import boto3
  4. import os
  5.  
  6. ec2 = boto3.client("ec2")
  7. iam = boto3.client("iam")
  8. Ec2Instance = boto3.resource("ec2").Instance
  9.  
  10. def get_ec2_instance(instance_id):
  11. return Ec2Instance(instance_id)
  12.  
  13. def acquire_instance_profile(profile_name):
  14. profile = iam.get_instance_profile(InstanceProfileName=profile_name)["InstanceProfile"]
  15. return profile
  16.  
  17.  
  18. def lambda_handler(event, context):
  19.  
  20. instance = get_ec2_instance(event['detail']['resourceId'])
  21.  
  22. if instance.iam_instance_profile is None:
  23. profile_name = os.environ['default_role']
  24.  
  25. profile = acquire_instance_profile(profile_name)
  26.  
  27. ec2.associate_iam_instance_profile(
  28. IamInstanceProfile={
  29. 'Arn': profile['Arn'],
  30. 'Name': profile_name
  31. },
  32. InstanceId=event['detail']['resourceId']
  33. )
  34.  
  35. return {
  36. "InstanceProfileName": profile_name, # No need for lexical-xform, the profile took the name we specified
  37. "InstanceProfileArn": profile["Arn"],
  38. "ActionTaken": "Assigned InstanceProfile \"{}\" to the Instance (it lacked a profile).".format(profile_name)
  39. }
  40. else:
  41. policy_arns = [ "arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM",
  42. "arn:aws:iam::257796259288:policy/calibre-webS3"
  43.  
  44. ]
  45.  
  46. role_name = iam.get_instance_profile(InstanceProfileName=instance.iam_instance_profile['Arn'].rsplit('/',1)[1])['InstanceProfile']['Roles'][0]['RoleName']
  47. attached_policies = iam.list_attached_role_policies(RoleName=role_name)
  48. print(attached_policies)
  49. attached_policy_arns =[]
  50.  
  51. for i in range(len(attached_policies['AttachedPolicies'])):
  52. attached_policy_arns.append(attached_policies['AttachedPolicies'][i]['PolicyArn'])
  53. print(attached_policy_arns)
  54. for policy in policy_arns:
  55. if policy not in attached_policy_arns:
  56. iam.attach_role_policy(RoleName=role_name, PolicyArn=policy)
  57. print(policy + "was attached.")
  58.  
  59.  
  60.  
  61. return {
  62. 'statusCode': 200,
  63. 'body': json.dumps('Hello from Lambda!')
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement