I am trying a create a role in AWS.
These role details are coming in from a json object.
shared ={
"mts":{
"account_id":"11111",
"workbench":"aaaaa",
"prefix":"zzzz"
},
"tsf":{
"account_id":"22222",
"workbench":"bbbbb",
"prefix":"yyyy"
}
}
role_arn = []
for x in shared:
role = f"arn:aws:iam::'{shared[x]['account_id']}':role/'{shared[x]['prefix']}'_role"
role_arn.append(role)
print(role_arn)
the out output:
["arn:aws:iam::'11111':role/'zzzz'_role", "arn:aws:iam::'22222':role/'yyyy'_role"]
the account_id
is being represented in ''
quotes which I want to avoid.
What I am expecting is something like this
["arn:aws:iam::11111:role/zzzz_role", "arn:aws:iam::22222:role/yyyy_role"]
How can I achieve this programmatically?
CodePudding user response:
I hope, this works for your solution,
import json
shared ={
"mts":{
"account_id":"11111",
"workbench":"aaaaa",
"prefix":"zzzz"
},
"tsf":{
"account_id":"22222",
"workbench":"bbbbb",
"prefix":"yyyy"
}
}
role_arn = []
for x in shared:
role = f"arn:aws:iam::'{shared[x]['account_id']}':role/'{shared[x]['prefix']}'_role"
if role.find("'") != -1:
role = role.replace("'", "")
role_arn.append(role)
print(json.dumps(role_arn))
CodePudding user response:
Perhaps
shared ={
"mts":{
"account_id":"11111",
"workbench":"aaaaa",
"prefix":"zzzz"
},
"tsf":{
"account_id":"22222",
"workbench":"bbbbb",
"prefix":"yyyy"
}
}
print(json.dumps(list(map(lambda v: f"arn:aws:iam::{v['account_id']}:role/{v['prefix']}_role", shared.values()))))
CodePudding user response:
You can simply use a list comprehension:
>>> [f"arn:aws:iam::{v['account_id']}:role/{v['prefix']}_role" for v in shared.values()]
['arn:aws:iam::11111:role/zzzz_role', 'arn:aws:iam::22222:role/yyyy_role']
or if you want JSON:
>>> import json
>>> print(json.dumps([f"arn:aws:iam::{v['account_id']}:role/{v['prefix']}_role" for v in shared.values()]))
["arn:aws:iam::11111:role/zzzz_role", "arn:aws:iam::22222:role/yyyy_role"]
CodePudding user response:
You can remove the single quotes inside the f-string and use the json
module to encode the dictionary. But you could also enumerate shared's values instead of the more complicated option of enumerating the keys and getting the values later. And this can all be done is a list comprehension without all that mucking about with maps, filters and lambdas.
role_arn = [f"arn:aws:iam::{acct['account_id']}:role/{acct['prefix']}_role"
for acct in shared.values()]
print(json.dumps(role_arn))