I am trying to construct a role in AWS where I am trying to have list of resources.
Below is an example
shared ={
"mts":{
"account_id":"11111",
"workbench":"aaaaa",
"prefix":"rad600-ars-sil,rad600-srr-sil-stage1,rad600-srr-sil-stage2"
},
"tsf":{
"account_id":"22222",
"workbench":"bbbbb",
"prefix":"yyyy"
}
}
I am trying to construct a list with
role_arn=[]
for key in shared:
role_arn.append(f"arn:aws:iam::'{shared[key]['account_id']}':role/'{shared[key]['workbench']}'_role")
here is my output:
["arn:aws:iam::'11111':role/'aaaaa'_role", "arn:aws:iam::'22222':role/'bbbbb'_role"]
I want the ''
to be removed from the list while appending into the list itself.
desired output:
["arn:aws:iam::11111:role/aaaaa_role", "arn:aws:iam::22222:role/bbbbb_role"]
I am trying my hands on python. IS there a way to achieve it?
CodePudding user response:
role_arn=[]
for key in shared:
role_arn.append(f"arn:aws:iam::{shared[key]['account_id']}:role/{shared[key]['workbench']}_role")
You don't need those '
unless you want them. You can remove it and the string formatting would still work as expected and get rid of the '
.
Most likely your concern was coming from not knowing the Lietral format strings. You don't need to use ''
before every variable. {}
takes care of it.
CodePudding user response:
This is my take on it
This uses dictionary comprehension to iterate over the shared dictionary instead of a for loop
shared ={
"mts":{
"account_id":"11111",
"workbench":"aaaaa",
"prefix":"rad600-ars-sil,rad600-srr-sil-stage1,rad600-srr-sil-stage2"
},
"tsf":{
"account_id":"22222",
"workbench":"bbbbb",
"prefix":"yyyy"
}
}
role_arn = [f"arn:aws:iam::{data['account_id']}:role/{data['workbench']}_role" for key, data in shared.items()]
print(role_arn)
Which gives the output
['arn:aws:iam::11111:role/aaaaa_role', 'arn:aws:iam::22222:role/bbbbb_role']
CodePudding user response:
To read a JSON object in Python, you can use the JSON module. Here is an example of how to use the JSON module to parse a JSON object stored in a string:
import json
json_string = '{"key": "value"}'
parsed_json = json.loads(json_string)
print(parsed_json) # Output: {'key': 'value'}
To remove quotes from a string in Python, you can use the replace() method. Here is an example of how to remove single quotes from a string:
string = "'Hello, World'"
new_string = string.replace("'", "")
print(new_string) # Output: Hello, World
You can also use the strip() method to remove quotes from the beginning and end of a string. Here is an example of how to remove both single and double quotes from the beginning and end of a string:
string = '"Hello, World"'
new_string = string.strip('"\'')
print(new_string) # Output: Hello, World