in iam_permissions_guardrails/constructs/service_control_policies/attachment_lambda/app.py [0:0]
def on_delete(event):
physical_id = event["PhysicalResourceId"]
print("delete resource %s" % physical_id)
props = event["ResourceProperties"]
print("delete resource with props %s" % props)
policy_id = props["PolicyId"]
account_targets = props.get("AccountTargets", [])
organization_unit_targets = props.get("OrganizationUnitTargets", [])
organizations_client = boto3.client("organizations")
for account in account_targets:
try:
organizations_client.detach_policy(PolicyId=policy_id, TargetId=account)
except organizations_client.exceptions.PolicyNotAttachedException:
logger.info(f"Already detached policy_id={policy_id} to {account}")
pass
except:
logger.exception(f"Error detached policy_id={policy_id} to {account}")
raise
for organization_unit in organization_unit_targets:
try:
organizations_client.detach_policy(
PolicyId=policy_id, TargetId=organization_unit
)
except organizations_client.exceptions.PolicyNotAttachedException:
logger.info(
f"Already detached policy_id={policy_id} to {organization_unit}"
)
pass
except:
logger.exception(
f"Error detached policy_id={policy_id} to {organization_unit}"
)
raise