0

I would like to iterate over all Resource sections of policy_json and replace all instances of DEV_ACCOUNT_ID with PROD_ACCOUNT_ID to produce a new dictionary prod_policy_json while doing the converse to produce dev_policy_json.

Why does the below script result in both dev_policy_json and prod_policy_json having the PROD_ACCOUNT_ID? How would I achieve my intended outcome? Thanks!

DEV_ACCOUNT_ID = "11111111111"
PROD_ACCOUNT_ID = "22222222222"

policy_json = {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "SesDeliveryLogsTopicDevSetTopicAttributes",
            "Effect": "Allow",
            "Action": [
            "sns:SetTopicAttributes"
            ],
            "Resource": [
                "arn:aws:sns:11111111111"
            ]
        },
        {
            "Sid": "AllRestApisReadWrite",
            "Effect": "Allow",
            "Action": [
                "apigateway:PUT",
                "apigateway:GET"
            ],
            "Resource": [
                "arn:aws:apigateway:eu-west-2::/22222222222",
                "arn:aws:apigateway:eu-west-2::/22222222222"
            ]
        }
    ]
}

dev_policy_json = policy_json.copy()
prod_policy_json = policy_json.copy()

for i, s in enumerate(policy_json["Statement"]):
    for j, r in enumerate(s["Resource"]):
        dev_policy_json["Statement"][i]["Resource"][j] = r.replace(PROD_ACCOUNT_ID, DEV_ACCOUNT_ID)
        prod_policy_json["Statement"][i]["Resource"][j] = r.replace(DEV_ACCOUNT_ID, PROD_ACCOUNT_ID)

print(dev_policy_json)
print("\n")
print(prod_policy_json)
  • 2
    Does this answer your question? [How to copy a dictionary and only edit the copy](https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy) (ignore the answer saying you should use `dict.copy()`) – mkrieger1 Mar 04 '22 at 10:31
  • copy.deepcopy(dict) was the answer I needed, thanks! – Duncan Ware Mar 04 '22 at 11:20

0 Answers0