Set today's date as environment variable

Viewed 5995

I need to set today's date as environment variable in my docker container.

What I am trying to do is to get today's date so I can use it to call some API with Logstash's http_poller plugin.

The solution I am thinking about is to get today's date using the command date +%Y%m%d

How can I set the result of this command as an environment variable at run time?

4 Answers

ARG should be what you are looking for:

FROM base

# to be able to use in Dockerfile
ARG now

# to store the value as environment variable in the image
ENV build_date=$now

Now you can build this with

# pass value explicitly
docker build --build-arg now="$(date +%Y%m%d)" .

# pass value from environment
export now="$(date +%Y%m%d)"
docker build --build-arg now .

This still requires to run date on the host since doing this inside the Dockerfile is not possible unfortunately:

  • The only way to execute arbitrary commands in the build is within a RUN statement; but
  • The only way to persist a variable into the environment of an image/container is with an ENV statement which can only use environment variables from outside the build

You could use a custom ENTRYPOINT tough and inject the date to the environment from a file:

FROM base

RUN date +%Y%m%d > /build-timestamp
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT /entrypoint.sh

entrypoint.sh:

#!/bin/bash

export BUILD_TIMESTAMP="$(cat /build-timestamp)"
exec "$@"

So according to your answer to my comment, if you want to have the variable set at runtime you need to inject it when you start your container

āœ— docker run -e TS=$(date +%Y%m%d) python:3.7-alpine env
TS=20201230
PYTHON_VERSION=3.7.9
HOME=/root

Here is the link to the docker documentation : https://docs.docker.com/engine/reference/run/#env-environment-variables

But you are confusing the Dockerfile with the container. A Dockerfile is a definition for building an image. This image is static. Then you start multiples containers from this base image.

So if your start 3 containers with the same image, according to your question you expect 3 different dates in your containers. So you see why you can't set a date or a command in a Dockerfile. The previous snippet does what you ask.

According to the documentation ENV only supports <key>=<value> entries, I see no way to put it there with a command. I suggest you drop the value into some file then read it when needed. Or, if you have a launch script, using RUN you can add export VAR_NAME=<value> to the launch script so that the variable is automatically added to the environment on launch.

My solution was to first do export command and then running service startup like this

CMD export INSTALL_DATE=$(date +%s) && python3 /product/server.py
Related