Newbie to AWS. I'm trying to add a inline policy to an IAM user using the putUserPolicy API as below. Running into Malformedpolicydocument as error code and syntax errors in policy as error message
// Attaches the policy document to the IAM user userName in the account
async putUserPolicy(userName: string, roleArn: string) {
let userPolicyData: any = null;
try {
// creates the policy document
const policyDocumentForUser = this.createUserPolicyDocument(roleArn);
const trustPolicyParamsForUser = {
PolicyDocument: JSON.stringify(policyDocumentForUser),
PolicyName: 'userPolciy',
UserName: userName
};
// attaching the policy document to the IAM user
userPolicyData = await this.iam.putUserPolicy(trustPolicyParamsForUser).promise();
this.logger.info(`Successfully created user policy for '${userName}'`);
} catch (error) {
this.logger.error(`Unable to create user policy role`, error);
throw error;
}
}
private createUserPolicyDocument(roleArn: string) {
const policyDocument = {
'statement': [
{
'Action': 'sts:AssumeRole',
'Resource': roleArn,
'Effect': 'Allow'
}
]
};
this.logger.debug('policyDocument:', policyDocument);
return policyDocument;
}
Tried giving the version to the policy as well, but observing the same error. I've been using single quotes for all the policy documents in my code base.
Adding reference documents: https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutUserPolicy.html
You probably have an issue with case-sensitivity.
Statementmust be capitalized.As a side-note: It considered good practice to avoid inline policies. You can create and attach managed policies instead. Also, according to the CIS AWS Foundations Benchmark, it is recommended that IAM policies be applied directly to groups and roles but not users.
The rationale behind this is that assigning privileges at the group or role level reduces the complexity of access management as the number of users grow. Reducing access management complexity may in-turn reduce opportunity for a principal to inadvertently receive or retain excessive privileges.