So I'm trying to automate through python what I normally do on the aws:iam console. This policy, validates as it is. As you see it here:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": [
"arn:aws:iam::123465790123:role/account-adm",
"arn:aws:iam::123465790123:role/account-adm",
"arn:aws:iam::123465790123:role/account-adm",
"arn:aws:iam::123465790123:role/account-adm"
]
}
]
}
Of course the account ids are fake, but it does validate .
So feeding that same policy to this bit of code does not work:
def create(iam, name, desc, policy):
response = iam.create_policy(
PolicyName = name,
Description = desc,
PolicyDocument=json.dumps(policy)
)
That is taken from aws recommended way of doing this, ofc: https://docs.aws.amazon.com/code-samples/latest/catalog/python-iam-create_policy.py.html
And this is the error I'm getting:
botocore.errorfactory.MalformedPolicyDocumentException: An error occurred (MalformedPolicyDocument) when calling the CreatePolicy operation: Syntax errors in policy.
This is confusing me a bit as I do not see why it would not work this way when it works on the console. So after way too much time googling this, I simply cannot find anything that would help me, or I'm completely misguided here.
Any help appreciated.
Thanks
I tried creating an IAM policy with the policy you have posted and ran in to the same issue. It seems that the output from json.dumps()
is the reason for the error.
You can do it this way though
import boto3
def create_iam_policy(iam, name, desc, policy):
response = iam.create_policy(
PolicyName = name,
Description = desc,
PolicyDocument= policy
)
return response
iam = boto3.client('iam')
my_managed_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": [
"arn:aws:iam::123465790123:role/account-adm",
"arn:aws:iam::123465790123:role/account-adm",
"arn:aws:iam::123465790123:role/account-adm",
"arn:aws:iam::123465790123:role/account-adm"
]
}
]
}
print(create_iam_policy(iam, 'test-policy', 'test desc', my_managed_policy))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.