def on_create()

in iam_permissions_guardrails/constructs/service_control_policies/attachment_lambda/app.py [0:0]


def on_create(event):
    props = event["ResourceProperties"]
    print("create new 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.attach_policy(PolicyId=policy_id, TargetId=account)
        except organizations_client.exceptions.DuplicatePolicyAttachmentException:
            logger.info(f"Already attached  policy_id={policy_id} to {account}")
            pass
        except:
            logger.exception(f"Error attaching policy_id={policy_id} to {account}")
            raise

    for organization_unit in organization_unit_targets:
        try:
            organizations_client.attach_policy(
                PolicyId=policy_id, TargetId=organization_unit
            )
        except organizations_client.exceptions.DuplicatePolicyAttachmentException:
            logger.info(
                f"Already attached  policy_id={policy_id} to {organization_unit}"
            )
            pass
        except:
            logger.exception(
                f"Error attaching policy_id={policy_id} to {organization_unit}"
            )
            raise

    physical_resource_id = str(uuid.uuid4())
    return {"PhysicalResourceId": physical_resource_id}