Joelgullander
Joelgullander

Reputation: 1684

Azure devops - Pass git commit SHA to dockerfile step

Here is my Dockerfile:

FROM node:alpine as builder
ENV GIT_SHA  ${WhatToSetHere} <--------------------------- Would like to set gitSHA here
RUN printenv
RUN mkdir -p /app
WORKDIR /app

COPY package.json ./
RUN yarn install

COPY . .
COPY public ./public

# RUN ls -la /src/

RUN yarn run build


FROM node:alpine
RUN mkdir -p /app
WORKDIR /app
ENV NODE_ENV production

COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/build ./build

EXPOSE 3000

CMD [ "yarn", "start:prod" ]

Here is my azure pipeline:

trigger:
  - master

pool:
  vmImage: "ubuntu-latest"

variables:
  buildConfiguration: "Release"
steps:
  - task: GitVersion@5
  - script: |
      echo '##vso[task.setvariable variable=buildVersion]$(GitVersion.FullSemVer")'
  - script: |
      echo //registry.npmjs.org/:_authToken=$(NPM_TOKEN) > .npmrc
    displayName: 'npm Authentication'
  - task: Docker@2
    inputs:
      containerRegistry: acrXXX
      repository: "XXX-client"
      command: "buildAndPush"
      Dockerfile: "**/Dockerfile"

  - task: PublishBuildArtifacts@1
    inputs:
      PathtoPublish: "$(Build.SourcesDirectory)/deploy/XXX-client"
      ArtifactName: "charts"
      publishLocation: "Container"

How can I get the commit SHA from the jenkins build and set it as env variable in my dockerfile? Is there any documentation you could point me towards which values that is included in a build?

Upvotes: 1

Views: 1526

Answers (2)

Aram Maliachi
Aram Maliachi

Reputation: 223

To your Dockerfile, add the following lines after the FROM step:

ARG GIT_SHA
ENV build_ref=$GIT_SHA

For your YAML pipeline, you need to split your build and push steps. We will use the predefined variable Build.SourceVersion within the build step as follows:

- task: Docker@2
  displayName: build
  inputs:
    command: build
    arguments: '--build-arg GIT_SHA=$(Build.SourceVersion)'

This will pass on the value of the Git reference SHA of the pipeline run on to your Dockerfile. You can call it in later steps as ${build_ref}, for example to print it into the logs you would add a step in your Dockerfile as follows:

RUN echo ${build_ref}

For further reading: Dockerfile reference: ARG, you can change the naming conventions just be sure to remain consistent both across the Dockerfile and the YAML pipeline.

Upvotes: 1

Krzysztof Madej
Krzysztof Madej

Reputation: 40673

Please check Build.SourceVersion variable.

The latest version control change of the triggering repo that is included in this build.

Git: The commit ID.
TFVC: the changeset.

Link to documentation.

Upvotes: 0

Related Questions