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 "pathtosourceaws.py", line 222, in <module>
create_user()
File "pathtosourceaws.py", line 197, in create_user
iam.update_assume_role_policy(
File "pathtovenevlibsite-packagesbotocoreclient.py", line 565, in _api_call
return self._make_api_call(operation_name, kwargs)
File "pathtovenevlibsite-packagesbotocoreclient.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"
2
Answers
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:
Below code executed without error:
To reproduce your situation, I did the following in the IAM management console:
I the repeated the process, but edited the Trust Policy using your code. It worked successfully.
As an experiment, I then edited the policy and changed the 12-digit Account number to
111111111111
. I then received the same error as you experienced:Invalid principal in policy
Therefore, the problem seems to be that you are using an invalid IAM User ARN in the
Principal
.