Search code examples
dockerenvironment-variablesmultiline

docker: poorly formatted environment: variable contains whitespaces


I have multi-line environment variables:

SINGLE_LINE=VALUE
MULTI_LINE=VA
LU E

I want to pass this environment variables using a file through --env-file parameter of docker run. When I pass this file to a Docker container, using --env-file, it fails with a message:

export SINGLE_LINE=VALUE
export MULTI_LINE="VA
LU E"
env > .env
docker run -ti --rm --env-file .env busybox sh
docker: poorly formatted environment: variable 'LU E' contains whitespaces.
See 'docker run --help'.

How to fix that?


Solution

  • The problem occur because the way docker parses this file it does not accept multi-line string and whitespaces in the key names. See relevant issue.

    Workaround. Strip all line-endings from multi-line variables:

    >.env
    for var in $(compgen -v | grep -Ev '^(BASH)'); do
        var_fixed=$(printf "%s" "${!var}" | tr -d '\n' )
        echo "$var=${var_fixed}" >>.env
    done
    

    Each line explained:

    1. >.env - make .env to be an empty file
    2. for var in $(compgen -v | grep -Ev '^(BASH)'); do - iterate over env keys
    3. var_fixed=$(printf "%s" "${!var}" | tr -d '\n' ) - remove new-lines from key value
    4. echo "$var=${var_fixed}" >>.env - write key=value pair to .env file