在 AWS 代码构建步骤中获取源回购提交哈希

Get source repo commit hash in AWS code build step

有没有办法从 AWS CodeBuild 构建步骤中获取提交哈希?我尝试使用 CODEBUILD_RESOLVED_SOURCE_VERSION 但它 returns IaC 存储库的 Commit Id 而不是源存储库的。

我知道如果你有执行 ID 有办法得到它:

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

但是我也没有 pipeline-execution-id。我只有 CODEBUILD_BUILD_ID.

找到适合我的解决方案:

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)

您可能需要将 artifactRevisions[?name=='src'] 中的“src”更改为对您的项目有效的任何值。

来自@IfTrue 下面的评论:

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

当 CodeBuild 运行 作为 CodePipeline 阶段的一部分并通过 webhook 调用 Source GitHub/CodeCommit 操作时,在 CodeBuild 中检索 Git Commit 消息:

  1. 确保您的 CodeBuild 项目的服务角色有权在管道

  2. 上执行 'ListPipelineExecutions'
  3. 在 Buildspec 'Install' 阶段添加以下内容:

    apt-get install jq
    
  4. 在需要获取提交消息的Buildspec中添加以下内容:

    COMMIT_MSG=$(aws codepipeline list-pipeline-executions  --pipeline-name <Pipeline_Name> --max-items 1 | jq -r '.pipelineExecutionSummaries[0].sourceRevisions[0].revisionSummary')
    
    echo $COMMIT_MSG
    

如果您使用的是 CodePipeline,则使用 CLI 查询的替代方法是 access namespaced variables from previous stages

  1. 编辑您要从中公开变量的管道阶段。给 namespace 赋值。这将允许您从该阶段引用 exposed variables。对于这个例子,假设我有一个名为 Source 的阶段,我将我的命名空间命名为 GitVariables。如果您使用 GitHub、GitLab、CodeCommit 或来源,变量看起来非常一致。
  2. 编辑调用 CodeBuild 的管道阶段以添加引用在步骤 #1 中公开的命名空间变量的环境变量。例如,如果我想向 CodeBuild 公开一个名为 GIT_COMMIT_ID 的环境变量,我将使用以下内容:

当管道运行时,环境变量将添加到名为 GIT_COMMIT_ID 的 CodeBuild 执行中。