I am facing a problem while calling the variable values within the double quote
Here's my code:
AccountID = ["1234567","5678912"]
for account in range(len(AccountID)):
response = sts.assume_role(RoleArn=(f"arn:aws:iam::{AccountID[account]}:role/Cloudbees_Jenkins"), RoleSessionName="learnaws-test-session")
print(response)
I have return response output with no variable values
File "test3.py", line 19
response = (RoleArn=(f"arn:aws:iam::{AccountID[account]}:role/Cloudbees_Jenkins"), RoleSessionName="learnaws-test-session")
^
SyntaxError: invalid syntax
how would i return an expected results like:
arn:aws:iam::1234567:role/Cloudbees_Jenkins
arn:aws:iam::5678912:role/Cloudbees_Jenkins
CodePudding user response:
You could use f-strings, a very convenient way to refer to variables inside print statements in python.
In your case, it would look like this:
response = f"arn:aws:iam::{int(AccountID[0])}:role/Cloudbees_Jenkins"
CodePudding user response:
response = (RoleArn=(f"arn:aws:iam::{AccountID[account]}:role/Cloudbees_Jenkins"), RoleSessionName="learnaws-test-session")
The problem here has nothing to do with generating the string.
The problem is that in Python the =
(assignment) operator does not produce an output value.
So the expression RoleArn = ...a_bunch_of_stuff...
only assigns that stuff to RoleArn
. It doesn't produce any output value that can be assigned to response
.
And the assignement RoleSessionName="learnaws-test-session"
doesn't produce any return value that can be assigned to be part of the tuple that is being assigned to RoleArn
.
So just break the code up into three lines:
RoleSessionName="learnaws-test-session"
RoleArn= f"arn:aws:iam::{AccountID[account]}:role/Cloudbees_Jenkins"
response = (RoleArn, RoleSessionName)
In recent Python versions (3.8 and newer) you can use the "walrus operator" :=
to both assign a value and return that value to be used in an expression, but in your code you should not because it IMO makes the code less clear.
CodePudding user response:
AccountID =[1234567,5678912] for i in AccountID: print("arn:aws:iam::",i,"role/Cloudbees_Jenkins")