How to pass env variables and arguments while building cloud build docker images?

421 Views Asked by At

I am trying to learn cloudbuild and starting with a simple project where,when I commit to a branch of a github, a docker container is build,which copies a bash script file and print its content.

I want to pass variables while building the container,so that it can be accessed in docker container,as well as the scripts.

Here are my files:

Dockerfile:

FROM ubuntu:latest
ARG _PID
ENV PJID=$_PID
COPY script.sh /
RUN echo "The ENV variable value is $PJID"
RUN chmod +x /script.sh
ENTRYPOINT ["/script.sh"]

script.sh

#!/bin/bash
echo "Hello, world! The new1  time is $(date)."
echo "$(PROJECT_ID)"

cloudbuild.yaml

steps:
- name: 'gcr.io/cloud-builders/docker'
  args: [ 'build', '-t', 'gcr.io/$PROJECT_ID/quickstart-docker-repo/test:tag1','--build-arg=ENV=$_PID', '.' ]
images:
- 'gcr.io/$PROJECT_ID/quickstart-docker-repo/test:tag1'
# [END cloudbuild_quickstart_build]
substitutions:
  _PID: $PROJECT_ID
options:
  logging: CLOUD_LOGGING_ONLY

But,when I pull and run this image of my cloudshell,it show below output.

Hello, world! The new1  time is Mon Jul 17 11:39:31 UTC 2023.
/script.sh: line 3: PROJECT_ID: command not found

I want to print the output of RUN echo "The ENV variable value is $PJID" which is in my container as well as output of echo "$(PROJECT_ID)" which is in my script file.

can someone tell me what's wrong here?

1

There are 1 best solutions below

4
guillaume blaquiere On

You are not on the right way! Many things to fix.

Firstly, your parameter in the docker build command '--build-arg=ENV=$_PID'. There is no arg in your dockerfile named ENV, so, it can't work.

Secondly, this dockerfile line RUN echo "The ENV variable value is $PJID" is only evaluated at Build time, not at runtime. You will never see this line after the container creation.

Then, this line echo "$(PROJECT_ID)" in your script is weird. $() syntax if for evaluating (like a command). If you want to print the env var value, use the bracket ${}.

Finally, still on this line echo "$(PROJECT_ID)", the project ID is not in the environment. You can set it at runtime (this time, the difference with Build arg that are evaluated at build time only). For that, you can run your container with this type of docker command docker run -e PROJECTID=GreatProject ...