in Lambda/BackupOrgPolicyManager/src/BackupOrgPolicyManager.py [0:0]
def create_and_attach_policies(policy_name, policy_description, policy_type, policy_content, policy_target_list,
assume_role_creds=None):
"""
Helper function to create and attach the policies to the targets
"""
try:
logger.info(f"Create and update policy with contents : {json.dumps(policy_content)} for name : {policy_name}")
org_client = boto3_client('organizations', AWS_REGION, assume_role_creds)
response = org_client.create_policy(
Content=json.dumps(policy_content),
Description=policy_description,
Name=policy_name,
Type=policy_type
)
if not 'Policy' in response:
logger.error("Error no policy received in response, returning..")
return False
except ClientError as e:
if e.response['Error']['Code'] == 'ConcurrentModificationException':
logger.info("Concurrent creation detected, sleeping 5s and trying again..")
sleep(5)
response = org_client.create_policy(
Content=json.dumps(policy_content),
Description=policy_description,
Name=policy_name,
Type=policy_type
)
else:
logger.error("Error occurred creating policy {}: {}".format(policy_name, e))
return False
logger.debug(f"Response: {response}")
policy_id = response['Policy']['PolicySummary']['Id']
logger.info(f'Policy creation complete, policy ID :{policy_id}, policy_name :{policy_name}')
logger.info(f"attach_policy for {policy_id} on {policy_target_list}")
# Attach the policy in target accounts
for policyTarget in policy_target_list:
try:
# To avoid ConcurrentModificationException
time.sleep(int(5))
logger.info(f"Attaching {policy_id} on Account {policyTarget}")
org_client.attach_policy(PolicyId=policy_id,
TargetId=policyTarget)
logger.info(f"Attached {policy_id} on Account {policyTarget}")
except ClientError as e:
if e.response['Error']['Code'] == 'ConcurrentModificationException':
logger.info("Concurrent update detected when attaching policy, sleeping 5s and trying again..")
sleep(5)
org_client.attach_policy(PolicyId=policy_id,
TargetId=policyTarget)
logger.info(f"Attached {policy_id} on Account {policyTarget}")
else:
logger.error("Error occurred creating policy {}: {}".format(policy_name, e))
except Exception as e: # pylint: disable = W0703
logger.error(str(e))
return policy_id