I'm trying to get the short git SHA of a commit from a CodeBuild build when it is triggered from a new commit in the main branch.
I know that CODEBUILD_RESOLVED_SOURCE_VERSION
contains the full commit SHA. I want to shrink this value to tag the output image before pushing it to ECR.
I tried in the buildspec.yml
:
version: 0.2
phases:
pre_build:
commands:
...
- COMMIT_ID=${CODEBUILD_RESOLVED_SOURCE_VERSION:0:8}
...
build:
commands:
...
- echo Tagging image with commit id $COMMIT_ID
- docker tag $REPOSITORY_URI/$IMAGE_REPO_NAME:latest $REPOSITORY_URI/$IMAGE_REPO_NAME:$COMMIT_ID
...
post_build:
commands:
...
- docker push $REPOSITORY_URI/$IMAGE_REPO_NAME:$COMMIT_ID
But I get:
[Container] 2022/07/07 11:30:05 Running command COMMIT_ID=${CODEBUILD_RESOLVED_SOURCE_VERSION:0:8}
/codebuild/output/tmp/script.sh: 4: Bad substitution
Why may this be?
CodePudding user response:
The Bad substitution
error likely comes from that the command is interpreted in a shell that does not understand the bash substitution syntax (for example sh
)
You could use cut
instead to extract the substring in a fully POSIX compliant way:
COMMIT_ID=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -b -8)
However if you are looking for the short commit hash it is safer to get that using git, then you will be sure you get just the right length (whether it is less equal to or more than 8) to be unique:
git rev-parse --short HEAD