Is it possible to define a Cloudformation Resource in-place?

Viewed 52

I have a resource definition

APITaskDefinition:
  Type: 'AWS::ECS::TaskDefinition'
  Properties:
    ...
    ExecutionRoleArn:
      <RoleADefinition here>
    ...
    TaskRoleArn:
      <RoleBDefinition here>
    ...

This would be great given these roles are only going to be used by this resoure APITaskDefinition and is considered best practice to use a specific role for each resource which is going to require one

1 Answers

I don't believe we can do that with CloudFormation.

Standard practice is to define all the resources together in single template and refer it.

  EcsTaskExecutionRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - ecs-tasks.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      Policies:
        - PolicyName: ecs-taskExecution
          PolicyDocument:
            Statement:
              - Effect: Allow
                Action:
                  - 'ecr:GetAuthorizationToken'
                  - 'ecr:BatchCheckLayerAvailability'
                  - 'ecr:GetDownloadUrlForLayer'
                  - 'ecr:BatchGetImage'
                  - 'logs:CreateLogStream'
                  - 'logs:PutLogEvents'
                Resource: '*'

and !GetAtt EcsTaskExecutionRole.Arn

      ContainerTaskdefinition:
        Type: 'AWS::ECS::TaskDefinition'
        Properties:
          Family: !Ref 'AWS::StackName'
          ExecutionRoleArn: !GetAtt EcsTaskExecutionRole.Arn <-- refer to task Arn
          TaskRoleArn: !GetAtt EcsTaskExecutionRole.Arn <-- refer to task Arn
          Cpu: '256'
          Memory: 1GB
          NetworkMode: awsvpc
          RequiresCompatibilities:
            - EC2
            - FARGATE
          ContainerDefinitions:
            - Name: !Ref 'AWS::StackName'
              Cpu: 10
              Essential: 'true'
              Image: !Ref Image
              Memory: '1024'

However, with AWS CDK, we can use a higher level construct which creates the roles with default permissions in most cases and can easily add additional permissions needed, when compiled creates the above cloudformation. Here is ECS Construct

Related