Dynamically build an image and use it for the pipelines

Is something like this possible? I want to dynamically build an image for the CI pipeline to use but I also wanna scope it to the given commit hash. I could have a cleanup cron job on the worker server.

pipeline:
  docker:
    image: docker
    commands:
      - docker build --rm path/to/dockerfile -t myimage:${DRONE_COMMIT}
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
  install:
    image: myimage:${DRONE_COMMIT}
    commands:
      - some-command
1 Like

yep, a similar approach is also discussed here https://github.com/drone/drone/issues/1609#issuecomment-318701814

Nice. The solution suggested on github however suffers from a race condition where two different commits can change the build definition. I wanted to scope the image with image: myimage:${DRONE_COMMIT} for this reason.

Will the native build syntax leverage docker cache layer?

1 Like

I wanted to scope the image with image: myimage:${DRONE_COMMIT} for this reason.

Correct. Using the commit hash should be fine.

Will the native build syntax leverage docker cache layer?

I would expect caching to work.

Unfortunately using DRONE_COMMIT in the image results in mapping values are not allowed in this context

Ok actually it was because on drone exec the variable is empty. I wonder if there is a way to provide a default value?

If you run drone exec --help you can see a list of all variables that can be provided as either command line flags or environment variables. You have a number of different options.

You can load from flag:

drone exec --commit-sha=8125f97c2147e9cae75aa793efe72048b8588297

Or load from flag with a dynamic value:

drone exec --commit-sha=$(git rev-parse HEAD)

Or provide as an environment variable:

DRONE_COMMIT_SHA=8125f97c2147e9cae75aa793efe72048b8588297 drone exec

The above environment variable can be saved to a .env file in the root of your repository. Drone will automatically read this file and load variables.