in functions/source/c1c_controltower_lifecycle.py [0:0]
def delete_cross_account_role(aws_account_id):
sts_session = assume_role(aws_account_id, c1cresources.ControlTowerRoleName)
client = sts_session.client("iam")
logger.info(f'Account is {boto3.client("sts").get_caller_identity()["Account"]}')
# If we want to force deletion of stray policies, we can un-comment the STS client and
# the policy_arns, then run a remove.
# sts_client = sts_session.client("sts")
# sts_identity = sts_client.get_caller_identity()
# partition = sts_identity["Arn"].split(":")[1]
policy_arns = [
# f"arn:{partition}:iam::{aws_account_id}:policy/{c1cresources.IamPolicyName}{i}"
# for i in ["0", "1", "2"]
]
try:
response = client.list_attached_role_policies(
RoleName=c1cresources.IamRoleName,
)
policy_arns = [x["PolicyArn"] for x in response["AttachedPolicies"]]
for arn in policy_arns:
try:
client.detach_role_policy(
RoleName=c1cresources.IamRoleName,
PolicyArn=arn,
)
logger.info(
f"Detached policy {arn} from role {c1cresources.IamRoleName}"
)
except Exception as e:
logger.error(
f"Failed to detach attached policy {arn} on role {c1cresources.IamRoleName} \
in account {aws_account_id}: {e}"
)
except Exception as e:
logger.error(
f"Failed to list attached role policies on role {c1cresources.IamRoleName} \
in account {aws_account_id}: {e}"
)
for arn in policy_arns:
try:
client.delete_policy(
PolicyArn=arn,
)
logger.info(f"Deleted policy {arn}")
except Exception as e:
logger.error(f"Failed to delete policy {arn}: {e}")
try:
client.delete_role(RoleName=c1cresources.IamRoleName)
logger.info("Deleted role")
except Exception as e:
logger.error(
f"Failed to delete role {c1cresources.IamRoleName} in account {aws_account_id}: {e}"
)