14

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: '*'
halfer
  • 19,824
  • 17
  • 99
  • 186
juan
  • 358
  • 1
  • 4
  • 12

1 Answers1

39

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.

UPDATE: (from comments)

With version 2 of CDK you have to add service-role/ to managed policy. So it looks like this:

ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonECSTaskExecutionRolePolicy')
LEQADA
  • 1,913
  • 3
  • 22
  • 41
dmahapatro
  • 49,365
  • 7
  • 88
  • 117
  • 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 – juan Jun 01 '20 at 14:33
  • Managed policy can be added in a different way altogether. I will update my answer to reflect that. Give me few minutes. – dmahapatro Jun 01 '20 at 15:17
  • @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. – dmahapatro Jun 01 '20 at 15:31
  • 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 – juan Jun 01 '20 at 17:41
  • 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. https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#cfn-iam-role-managepolicyarns . In cases where you are writing your own customer managed policies that is where we normally use `Policies` property – dmahapatro Jun 01 '20 at 20:15
  • @user2081381 Here is an example: https://aws.amazon.com/premiumsupport/knowledge-center/cloudformation-attach-managed-policy/ – dmahapatro Jun 01 '20 at 20:17
  • @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 ? – logan Aug 27 '20 at 19:43
  • @logan Should be easy. Create a customer managed policy and then attach it to the role. Here is the detail: https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Policy.html#attach-wbr-to-wbr-rolerole – dmahapatro Aug 28 '20 at 17:13
  • @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 : https://stackoverflow.com/questions/63623519/create-custom-aws-iam-policy-using-cdk – logan Aug 28 '20 at 19:16
  • It seems like if you want to use ECS Exec, you must also add `AmazonSSMManagedInstanceCore` now as a Managed Policy as well. – CodeSammich Nov 20 '21 at 02:52
  • 1
    With version 2 of CDK (I'm using 2.55) I had to add "service-role/" to ManagedPolicy.fromAwsManagedPolicyName('AmazonECSTaskExecutionRolePolicy') so it looks like this: ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonECSTaskExecutionRolePolicy') – Chris Mitchell Feb 16 '23 at 01:06
  • @ChrisMitchell Thank you for commenting here. Do you mind if I update the answer to capture your feedback w.r.t CDKv2? – dmahapatro Feb 16 '23 at 18:17
  • 1
    ya go for it. I was using your answer to solve an issue i had but had to figure out why it wouldn't load that managed role. – Chris Mitchell Feb 16 '23 at 22:20