AWS CDK - role and policy creation

25,845

You should refer to API reference document to get a clear picture. There are examples for such use cases.

However, since you have already asked here and my hands has been itchy to provide you with an answer, so here goes the TypeScript implementation of just the IAM part:

import { 
   ManagedPolicy, 
   Role, 
   ServicePrincipal, 
   PolicyStatement, 
   Effect 
} from '@aws-cdk/aws-iam';

....
....

const ecsFargateServiceRole = new Role(this, 'FargateTaskExecutionServiceRole', {
  assumedBy: new ServicePrincipal('ecs-tasks.amazonaws.com')
});

// Add a policy to a Role
ecsFargateServiceRole.addToPolicy(
  new PolicyStatement({
    effect: Effect.ALLOW,
    resources: ['*'],
    actions: [            
      'ecr:GetAuthorizationToken',
      'ecr:BatchCheckLayerAvailability',
      'ecr:GetDownloadUrlForLayer',
      'ecr:BatchGetImage',
      'logs:CreateLogStream',
      'logs:PutLogEvents'
    ]
  })
);

// Add a managed policy to a role you can use
ecsFargateServiceRole.addManagedPolicy(
    ManagedPolicy.fromAwsManagedPolicyName('AmazonECSTaskExecutionRolePolicy')
);

....
....

UPDATE:

When you are adding an AWS managed policy to a role, you can get the managed policy as a reference by its name or by its ARN. The important part is that if an AWS Managed policy is used as above by its name or ARN, then you will not need to use the policy statement explicitly. From my answer above, you can use the managed policy approach rather than using the policy statement.

An easy way to define the role now would be:

const ecsFargateServiceRole = new Role(this, 'FargateTaskExecutionServiceRole', {
  assumedBy: new ServicePrincipal('ecs-tasks.amazonaws.com'),
  managedPolicies: [
    ManagedPolicy.fromAwsManagedPolicyName('AmazonECSTaskExecutionRolePolicy')
  ]
});

Note that I have excluded the constructor for the Construct for brevity.

Share:
25,845
user2081381
Author by

user2081381

Updated on March 14, 2021

Comments

  • user2081381
    user2081381 about 3 years

    How can I translate this CloudFormation to CDK (JavaScript or Java)? I was trying to do it, but this is the first time that I work with CDK and I'm not sure how to do it.

    FargateTaskExecutionServiceRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service: 
              - ecs-tasks.amazonaws.com
          Action:
            - sts:AssumeRole
      Policies:
        - PolicyName: AmazonECSTaskExecutionRolePolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
            - Effect: Allow
              Action:
                - 'ecr:GetAuthorizationToken'
                - 'ecr:BatchCheckLayerAvailability'
                - 'ecr:GetDownloadUrlForLayer'
                - 'ecr:BatchGetImage'
                - 'logs:CreateLogStream'
                - 'logs:PutLogEvents'
              Resource: '*'
    
  • user2081381
    user2081381 almost 4 years
    Hi dmahapatro.Thank you so much for your answer. Is it not necessary to include the name of the policy (PolicyName: AmazonECSTaskExecutionRolePolicy)? Because she is a Managed Policy
  • dmahapatro
    dmahapatro almost 4 years
    Managed policy can be added in a different way altogether. I will update my answer to reflect that. Give me few minutes.
  • dmahapatro
    dmahapatro almost 4 years
    @user2081381 I have updated the answer. In your use case you only need to use the managed policy they way I have shown, you do not need to use addToPolicy(). Let me know if you still have any question.
  • user2081381
    user2081381 almost 4 years
    Does that mean that the policy in the cloudformation is wrong? Shouldn't I use a Managed policy and use the attributes actions, effects and resources? The policy was created that way, and it works today like that
  • dmahapatro
    dmahapatro almost 4 years
    Cloudformation template for IAM Role provides a property ManagedPolicyArns where you can specify the ARN of the managed policy that you want to attach to the role. docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/… . In cases where you are writing your own customer managed policies that is where we normally use Policies property
  • dmahapatro
    dmahapatro almost 4 years
    @user2081381 Here is an example: aws.amazon.com/premiumsupport/knowledge-center/…
  • logan
    logan over 3 years
    @dmahapatro: thanks but this is not creating a custom policy but creates inline policies which can't be reused with policy arn. How do we create custom policy ?
  • dmahapatro
    dmahapatro over 3 years
    @logan Should be easy. Create a customer managed policy and then attach it to the role. Here is the detail: docs.aws.amazon.com/cdk/api/latest/docs/…
  • logan
    logan over 3 years
    @dmahapatro: Thanks. I tried that out no luck with Managed policy. I posted a question, could you pls help with sample custom policy creation part : stackoverflow.com/questions/63623519/…
  • CodeSammich
    CodeSammich over 2 years
    It seems like if you want to use ECS Exec, you must also add AmazonSSMManagedInstanceCore now as a Managed Policy as well.