Git SHA: echo $CI_COMMIT_ID to a file before docker build step


#1

Hi,

I am trying to echo the git SHA ${CI_COMMIT_ID} to a text file in my project root as part of a step, before the docker build runs. This is so that a running container of my application will be able to echo which version it is running.

I have tried a basic command: echo ${CI_COMMIT_ID} > VERSION.info, but my docker container ended up with an empty VERSION.info file, which is unchanged from how I committed it to git.

Has anyone done something similar?


#2

Hey, there -

You can’t write a script before any Docker build, but you could do something like:

prebuild:
 image: alpiine:3:1
 volumes:
    - ./tmp:/tmp

your_main_app:
  build:
    image: yourimage/name
    dockerfile_path: Dockerfile
  volumes_from:
     - prebuild

and

- service: prebuild
  command: write-sha.sh

In this example, a mimimal container is being used to write your sha - and specifically to write it to a host volume that you share with your main application container.

Does this make sense?


#4

Thanks Ethan.

Here is the complete solution I am using:

in codeship-services.yml:

prebuild:
  image: yikaus/alpine-bash
  volumes:
    - ./:/src

app:
  build:
    image: myimage/name
    dockerfile_path: Dockerfile

in codeship-steps.yml

- service: prebuild
  command: /src/deploy/version-info.sh

deploy/version-info.sh

#!/bin/bash
echo ${CI_COMMIT_ID:0:7} > /src/VERSION.info

VERSION.info is then available in my project root when the app is being built from my main Dockerfile.

I found the volumes_from: prebuild you recommended was unnecessary for me, since that is the main build, so there are no volume mounts? (This actually had me confused for quite a bit, but then I got rid of it and stuff made sense again). I guess I would use the volumes trick if I had any intermediate steps though which needed to share some files between steps.

Thanks again for your help.

PS. I’ve done the above in Docker Cloud / Wercker and now Codeship. It always seems like a workaround and hacky. Is there not more of a calling for this type of thing from the users? For us it’s a pre-requisite to have confidence in our CI/CD, and it’s a pity to have to do so much setup work to try and find a solution which works on each platform.


#5

Can this be done with Build Args now? It would be great to have a less hacky solution for this.