Enable Azure Container Instances to Read Environment Variables from the Environment Variables File
  • 23 Sep 2022
  • 1 Minute to read
  • Contributors
  • Comment
  • Dark
    Light
  • PDF

Enable Azure Container Instances to Read Environment Variables from the Environment Variables File

  • Comment
  • Dark
    Light
  • PDF

#ServerlessTips - Azure Container Instances
Author: Rahul Rai Azure MVP

Docker Compose allows users to store common environment variables in a file named .env, which is placed in the project directory. The docker run command, which runs a container from an image, allows you to load the environment variables from a file by specifying the file's name as the value of the --env-file parameter.

The environment variables file should use the syntax < variable >=value. Docker sets the variable's name as the name of the environment variable and the value as the value of the environment variable.

The az container create command allows you to specify the environment variables for your container through the --environment-variables parameter. The parameter takes space-separated values in key=value format. Translating the parameters from a file to the space-separated key-value format can be challenging for containers with several environment variables.

We can fix this problem with a tiny script that reads the variables and values stored in the .env file and translate them to the format expected by the --environment-variables parameter.

Let's explore this tip with a quick demo. Create a file named .env in a folder with the following content:

KEY1=VALUE1
KEY2=VALUE2

Use the following command to convert the text to space separated key-value pair:

envs=$(cat .env | awk '{printf "%s ",$0} END {print ""}' )

The following screenshot shows the text format conversion from the previous command:

Picture3(14)

Let's now send these parameters to a new NGINX container instance application that we will create with the following command:

az container create \
-g <RESOURCE GROUP NAME> \
--name nginx \
--image registry.hub.docker.com/library/nginx \
--ip-address Public \
--environment-variables $envs

Let's inspect the container instance on the Azure portal. Click on the Containers option and the Properties tab on the next blade. You will find the environment variables for your container listed here.

Picture4(12)


Was this article helpful?