Service Role for CodeBuild


Do you notice anything that is not right in the following CloudFormation template?

...
Resources:
  CodeBuildServiceRole: # IAM role for the codebuild project. 
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub ${ProjectName}-CodeBuild-ServiceRole
      Path: /team-abc/
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Action: ['sts:AssumeRole']
            Effect: Allow
            Principal:
              Service: ['codebuild.amazonaws.com']
      Policies:
        - PolicyName: !Sub ${ProjectName}-CodeBuild-Policy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action: # Allow to push logs to cloudwatch
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Effect: Allow
                Resource:
                  - !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}
                  - !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}:*
      ...

  CodeBuildProject:
    Type: AWS::CodeBuild::Project
    Properties:
      Name: !Ref ProjectName
      Artifacts:
        Type: NO_ARTIFACTS
      Environment:
        Type: LINUX_CONTAINER
        ComputeType: BUILD_GENERAL1_SMALL
        Image: aws/codebuild/amazonlinux2-x86_64-standard:3.0
      ServiceRole: !Ref CodeBuildServiceRole
      ...
...

According to AWS::CodeBuild::Project, the ServiceRole has to be ARN. When use !Ref CodeBuildServiceRole in the above template, it refers to the Role name which could cause issues especially when you are not using the default path /. So the right one should be !GetAtt CodeBuildServiceRole.Arn

ServiceRole
The ARN of the AWS Identity and Access Management (IAM) role that enables AWS CodeBuild to interact with dependent AWS services on behalf of the AWS account.

Required: Yes

Type: String

Minimum: 1

Update requires: No interruption

But if you are creating AWS::IAM::InstanceProfile, the Roles should be the role names. It may work if you use ARN here, but better stick with the documentation. Evils are in the details!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s