This question is somewhat connected to the discussion found here: How can I use the AWS CLI to add a trust policy to a role?
Previously, I encountered a problem adding a policy via the AWS CLI. It was resolved thanks to the solution shared by @john-rotenstein
However, I'm encountering a similar issue when attempting to add the policy using the boto3 library. Currently, I am already using the full content of the policy.
Code:
trust_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
},
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"AWS": f"arn:aws:iam::{account_id}:user/{user_name}"
},
"Action": "sts:AssumeRole"
}
]
}
iam.update_assume_role_policy(
RoleName=role_name,
PolicyDocument=json.dumps(trust_policy)
)
Error:
Traceback (most recent call last):
File "\path\to\source\aws.py", line 222, in <module>
create_user()
File "\path\to\source\aws.py", line 197, in create_user
iam.update_assume_role_policy(
File "\path\to\venev\lib\site-packages\botocore\client.py", line 565, in _api_call
return self._make_api_call(operation_name, kwargs)
File "\path\to\venev\lib\site-packages\botocore\client.py", line 1021, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.errorfactory.MalformedPolicyDocumentException: An error occurred (MalformedPolicyDocument) when calling the UpdateAssumeRolePolicy operation: Invalid principal in policy: "AWS":"arn:aws:iam::xxxxxxxxxxxx:user/teli_tst_user"
After few trial and error, I was able to solve the issue. Initially I was trying to create the policy soon after the role is created in the script.
When I added a wait for 60 seconds, the code executed without any error.
Below code returns error:
iam = boto3.client('iam')
iam.create_role(...)
iam.attach_role_policy(...)
iam.update_assume_role_policy(...)
Below code executed without error:
iam = boto3.client('iam')
iam.create_role(...)
iam.attach_role_policy(...)
time.sleep(60)
iam.update_assume_role_policy(...)