in migration/bring-your-own-role/byor.py [0:0]
def _replace_role_arn_in_policies(policies_to_update, iam_client, old_role_arn, new_role_arn, execute_flag):
for policy_arn in policies_to_update:
policy = iam_client.get_policy(PolicyArn=policy_arn)['Policy']
policy_document = iam_client.get_policy_version(
PolicyArn=policy_arn,
VersionId=policy['DefaultVersionId']
)['PolicyVersion']['Document']
# Replace the role ARN if source_role is present in customer managed policy
policy_str = json.dumps(policy_document)
if old_role_arn in policy_str:
update_policy_str = policy_str.replace(old_role_arn, new_role_arn)
print(f"Updated policy doc for {policy['PolicyName']}: {update_policy_str}\n")
if execute_flag:
iam_client.create_policy_version(
PolicyArn=policy_arn,
PolicyDocument=update_policy_str,
SetAsDefault=True
)
print(f"Successfully updated policy {policy['PolicyName']} with new version after replacing execution role content.")
else:
print(f"Policy {policy['PolicyName']} update skipped, set --execute flag to True to do the actual update.\n")