Home > Software design >  How to get CodeBuild project name from buildspec file
How to get CodeBuild project name from buildspec file

Time:12-31

This is my buildspec file to build an Angular, React, Vue or similar project through AWS CodeCommit and publish the resulting artifact to an S3 bucket:

version: 0.2
env:
  variables:
    S3_BUCKET: "my-bucket"
phases:
  install:
    runtime-versions:
      nodejs: 16
  pre_build:
    commands:
      - echo Installing source NPM dependencies...
      - npm install
  build:
    commands:
      - echo Build started on `date`
      - npm run build
  post_build:
    commands:
      - aws s3 cp dist s3://${S3_BUCKET} --recursive
      - echo Build completed on `date`

What I would like to do is to use a subfolder with the name of the project when publishing the result files in the bucket. Now all files go to my-bucket but I would like them to go to my-bucket/name-of-the-project

I could change the post-build command to something like

    - aws s3 cp dist s3://${S3_BUCKET}/name-of-the-project --recursive

That way it would be always the same directory name. What I want is to get dynamically the name of the CodeBuild project or from the package.json or similar to make that directory match the project name.

CodePudding user response:

Here are two ways to read a project identifier from the build context at run-time:

Option 1: Read the project name from package.json:

PROJECT_NAME=$(cat package.json | jq -r '.name')
echo $PROJECT_NAME # -> name-of-the-project

Option 2: Extract the CodeCommit repo name from the source URL. Each CodeBuild execution exposes several environment variables, including CODEBUILD_SOURCE_REPO_URL.

echo $CODEBUILD_SOURCE_REPO_URL # -> https://git-codecommit.us-east-1.amazonaws.com/v1/repos/my-repo

REPO_NAME=$(echo $CODEBUILD_SOURCE_REPO_URL | awk -F\"/\" '{print $NF}') # split the url at '/', return the last item
echo $REPO_NAME # -> my-repo

Pass one of the captured names to the S3 command:

aws s3 cp dist s3://${S3_BUCKET}/${PROJECT_NAME} --recursive
  • Related