Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get source repo commit hash in AWS code build step

Is there a way to get the commit hash from inside an AWS CodeBuild build step? I tried using the CODEBUILD_RESOLVED_SOURCE_VERSION but it returns the IaC repo's Commit Id instead of the source repo's.

I know there is a way to get it if you have the execution id:

aws codepipeline get-pipeline-execution --pipeline-name my-pipeline --pipeline-execution-id e550c757-434a-4c94-8e2e-5122ca14d861

However I don't have the pipeline-execution-id either. I only have the CODEBUILD_BUILD_ID.

like image 584
sashoalm Avatar asked Mar 03 '23 03:03

sashoalm


2 Answers

If you're using CodePipeline, an alternative to using the CLI to query would be to access namespaced variables from previous stages.

  1. Edit the pipeline stage that you would like to expose variables from. Give a value to namespace. That will allow you to reference exposed variables from that stage. For this example, let's say I have a stage called Source and I name my namespace GitVariables. Variables seem pretty consistent if you're using GitHub, GitLab, CodeCommit, or sources. Set namespace for CodePipeline action
  2. Edit the pipeline stage that calls CodeBuild to add an environment variable that references the namespaced variable exposed in step #1. For example, if I want to expose an environment variable to CodeBuild called GIT_COMMIT_ID, I would use the following: CodePipeline - set environment variable

When the pipeline runs, an environment variable will be added to CodeBuild execution called GIT_COMMIT_ID.

like image 93
Jim Geurts Avatar answered Mar 05 '23 16:03

Jim Geurts


Found a solution that works for me:

PIPELINE_EXECUTION_ID=$(aws codepipeline get-pipeline-state --region ${AWS_REGION} --name my-pipeline --query 'stageStates[?actionStates[?latestExecution.externalExecutionId==`'${CODEBUILD_BUILD_ID}'`]].latestExecution.pipelineExecutionId' --output text)
SOURCE_REPO_COMMIT_HASH=$(aws codepipeline get-pipeline-execution --pipeline-name my-pipeline --pipeline-execution-id $PIPELINE_EXECUTION_ID --query "pipelineExecution.artifactRevisions[?name=='src'].revisionId" --output text)

You might need to change "src" in artifactRevisions[?name=='src'] to whatever value is valid for you project.

From @IfTrue's comment below:

Sidenote for other readers: the portion sashoalm mentions that might need changed ('src') is the name of the Output Artifact in the "action group" inside of the "stage" in your CodePipeline where it watches for the CodeCommit change. Also this part of the AWS docs explains the magic behind the query: docs.aws.amazon.com/cli/latest/reference/codepipeline/… – IfTrue

like image 45
sashoalm Avatar answered Mar 05 '23 17:03

sashoalm