Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create custom AWS IAM policy using CDK

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

like image 745
logan Avatar asked Jan 24 '23 18:01

logan


1 Answers

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);
like image 152
dmahapatro Avatar answered Feb 11 '23 08:02

dmahapatro