66
loading...
This website collects cookies to deliver better user experience
AWS::CodeBuild::SourceCredential
resource type should only be used once per ServerType
. Unfortunately, I spent close to an hour searching around and trying to figure this out. The error that held me up looked something like thisFailed to call ImportSourceCredentials, reason: Access token with server type GITHUB already exists. Delete its source credential and try again.
Parameters
set to assume an SSM parameter exists called codebuild-github-token
. This can be changed to whatever name you would like, but I do not recommend copy and pasting a personal access token directly into the CloudFormation parameters.Parameters:
GitHubAccessToken:
Type: AWS::SSM::Parameter::Value<String>
Description: Name of parameter with GitHub access token
Default: codebuild-github-token
NoEcho: True
Resources:
CodeBuildCredentials:
Type: AWS::CodeBuild::SourceCredential
Properties:
ServerType: GITHUB
AuthType: PERSONAL_ACCESS_TOKEN
Token: !Ref GitHubAccessToken
Parameters:
GitHubUrl:
Type: String
Description: URL for GitHub repo i.e. https://github.com/username/repository
Resources:
CodeBuildRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- codebuild.amazonaws.com
Action:
- sts:AssumeRole
Description: !Sub "IAM Role for ${AWS::StackName}"
Path: '/'
Policies:
- PolicyName: root
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- cloudformation:*
- codebuild:*
- logs:*
Resource: '*'
CodeBuild:
Type: AWS::CodeBuild::Project
Properties:
Description: CodeBuild with GitHub webhook
Triggers:
BuildType: BUILD
Webhook: True
FilterGroups:
- - Type: EVENT
Pattern: PUSH,PULL_REQUEST_MERGED
- Type: HEAD_REF
Pattern: ^refs/heads/main$
ExcludeMatchedPattern: false
ServiceRole: !GetAtt CodeBuildRole.Arn
Artifacts:
Type: NO_ARTIFACTS
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/standard:4.0
EnvironmentVariables:
- Name: MY_ENV_VAR
Value: something
Type: PLAINTEXT
Source:
Type: GITHUB
Location: !Ref GitHubUrl
TimeoutInMinutes: 10
CodeBuildLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/codebuild/${CodeBuild}"
RetentionInDays: 7
Outputs:
ProjectName:
Value: !Ref CodeBuild
Description: CodeBuild project name
FilterGroups
are currently set up to only trigger on merges and direct pushes to a branch called main
, which might need to change based on your requirements. Lastly, the CodeBuild instance is expected a file called buildspec.yml
to be present in the repo’s root directory. If you do not know what a buildspec
is, please read this documentation (it is pretty much just a bash script to run when CodeBuild is triggered).