4
votes

As per doc : https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Policy.html

I could create my own policy and attach to role but it is not creating a new policy rather attached as inline policy to the role. I want to create a custom policy with an arn so that I can attach to other roles I want

Things I tried

new Policy(..)
new iam.PolicyStatement()
addStatements()
attachToRole()

Please let me know how can I create custom managed policy

1

1 Answers

8
votes

I should have been more specific in the previous question and should have said to use ManagedPolicy. Here is a the solution you are looking for :

 const role = new Role(this, 'MyRole', {
   assumedBy: new ServicePrincipal('ec2.amazonaws.com'),
 });

 const policy = new ManagedPolicy(this, "MyManagedPolicy", {
   statements: [
     new PolicyStatement({
       effect: Effect.ALLOW,
       actions: ["s3:*"],
       resources: ["*"]
     })
   ],
   roles: [role]
 });

 // Either use roles property inside ManagedPolicy or use attachToRole below,
 // Both will yield the same result
 // Creates a managed policy and then attaches the policy to role

 // policy.attachToRole(role);