← Blog 18. Juni 2018 · Amazon Web Services · AWS CloudFormation

Use GitHub source in AWS CodeBuild Project using AWS CloudFormation

AWS CodeBuild with GitHub in North Virigina

I wanted to create an AWS CodeBuild project using AWS CloudFormation, which checks out its sources from GitHub and is triggered via GitHub Webhooks. From these sources, a Node.js application should be built using a self-created docker image stored in ECR (Elastic Container Registry).

Therefore I defined the following template:

AWSTemplateFormatVersion: 2010-09-09
Resources:

  CodeBuildServiceRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub CodeBuildRole-${AWS::StackName}
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          -
            Effect: "Allow"
            Principal:
              Service:
                - "codebuild.amazonaws.com"
            Action:
              - "sts:AssumeRole"
      Path: /service-role/
      Policies:
        -
          PolicyName: "CodeBuildAccessPolicies"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              -
                Effect: "Allow"
                Action:
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
                Resource:
                  - !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/*

  CodeBuildProject:
    Type: AWS::CodeBuild::Project
    Properties:
      Name: Sample-CodeBuildProject
      ServiceRole: !GetAtt CodeBuildServiceRole.Arn
      Artifacts:
        Type: no_artifacts
      Environment:
        Type: LINUX_CONTAINER
        ComputeType: BUILD_GENERAL1_SMALL
        Image: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/codebuild-npm-docker:latest
      Source:
        Auth:
          Type: OAUTH
        Location: https://github.com/username/repository.git
        Type: GITHUB
      Triggers:
        Webhook: true
      TimeoutInMinutes: 10

Quelle: Gist auf GitHub

At the first try the stack creation failed with the following error message:

No Access token found, please visit AWS CodeBuild console to connect to GitHub (Service: AWSCodeBuild; Status Code: 400; Error Code: InvalidInputException; Request ID: ab458603-6fd4-11e8-9310-ff116e0423f9)

To get rid of this error message it's necessary to set up the AWS OAuth application to have access to your repositories.

Therefore you have to navigate to the AWS CodeBuild console, create a project and select GitHub as source provider. The project does not need to be saved, it is only important to connect to GitHub.

AWS CodeBuild GitHub AWS CodeBuild GitHub

The next time I tried to deploy the CloudFormation stack, the error message did not appear and the CodeBuild project was created successfully.

CloudFormation CodeBuild CloudFormation CodeBuild