Middle+
How can a dynamic attribute from CI be passed to Docker during image build, for example, a project identifier, if environment variables are not used?
sobes.tech AI
Answer from AI
Build arguments can be used.
# Syntax for defining a build argument with a default value
ARG PROJECT_ID=default
# Using the argument in a COPY instruction, for example
COPY ./app_${PROJECT_ID}.jar /app/app.jar
# Or in a RUN instruction
RUN echo "Project ID is ${PROJECT_ID}"
In CI/CD pipelines, you can pass the argument value during image build using the --build-arg flag:
# Example build command in CI
docker build --build-arg PROJECT_ID=$CI_PROJECT_ID -t my-image:${CI_COMMIT_SHORT_SHA} .
Here, $CI_PROJECT_ID is a CI variable containing the project identifier.
Another method is to use a variable file for the build, which is more like an environment variable usage:
# Dockerfile remains unchanged
ARG PROJECT_ID=default
COPY ./app_${PROJECT_ID}.jar /app/app.jar
File build-args.env:
PROJECT_ID=my-specific-project
Build command with a file:
docker build --build-arg PROJECT_ID=$(cat build-args.env) -t my-image:${CI_COMMIT_SHORT_SHA} .
Another option is generating a file inside the Dockerfile using RUN:
ARG PROJECT_ID=default
# Generate a file with the project identifier
RUN echo "${PROJECT_ID}" > /app/project_id.txt
# The application can then use this file