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



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} >, but my docker container ended up with an empty file, which is unchanged from how I committed it to git.

Has anyone done something similar?


Edit: You can now accomplish this directly by using the default CI/CD env vars as build arguments! See here for more info:

Hey, there -

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

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

    image: yourimage/name
    dockerfile_path: Dockerfile
     - prebuild


- service: prebuild

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?


Thanks Ethan.

Here is the complete solution I am using:

in codeship-services.yml:

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

    image: myimage/name
    dockerfile_path: Dockerfile

in codeship-steps.yml

- service: prebuild
  command: /src/deploy/


echo ${CI_COMMIT_ID:0:7} > /src/ 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.


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


@Ethan_Jones Hello, is there an easier way to do this yet? It’s a very common use-case.


Another related thing: it’s not clear when the variables listed at are available. Are those all run-time-only environment variables?


Hey, there -

It can indeed now be done in a better way! The default CI/CD env vars can now also be used as build arguments natively, with just a little bit of configuration.

You can find more info here:

And, please feel free to ask me any questions about it.