How to replace .env file placeholders with deployment variables in bitbucket pipeline

Viewed 1430

I have a bitbucket repository. I have Deployment environment variables in bitbucket:

BITBUCKET_VARIABLE_PORT : 8080

In my bitbucket-pipelines.yaml script I can Write the variable into the .env file like this:

<...>
step: &deploy-to-environment
        name: Deploy to environment
        deployment: environment
        caches:
          - node
        script:
          - echo Create .env file
          - echo "PORT=$BITBUCKET_VARIABLE_PORT" > .env          
          - cat .env
<...>

But I would like to avoid rewriting the whole lines of .env file.

Is it possible to implement the following?

  1. I would like to have .env file with placeholders (.env file content):
    <...>
    PORT=<BITBUCKET_VARIABLE_PORT>
    HOST=<BITBUCKET_VARIABLE_HOST>
    <...>
  1. Replace these placeholders in yaml script section:
    <...>
        step: &deploy-to-environment
                name: Deploy to environment
                deployment: environment
                caches:
                  - node
                script:
                  - <replace_placeholders_here_in_script>
    <...>
2 Answers

You can use sed to replace string in .env file

sed -i "s/BITBUCKET_VARIABLE_PORT/...xxxx.../" .env
sed -i "s/BITBUCKET_VARIABLE_HOST/...hostname.../" .env

You can use also variables for replacement

MYPORT=XXX
sed -i "s/BITBUCKET_VARIABLE_PORT/$MYPORT/" .env

I had the same issue lately and didn't want to include 1 by 1 the env variable, what I ended up doing:

#1 Create in repository a .env.example file (This file will hold variable that required for this repository without values or default values that are not sensitive)

APP_NAME=MyApp
APP_ENV=
APP_KEY=
APP_DEBUG=true

Then I created a pipeline.sh

echo "[+] Building enviroment variables"

# Get contents of example file
ENV_CONTENT=$(cat ./.env.example)

# Output the content into sh script
echo "#! /bin/bash
echo \"
${ENV_CONTENT}
\"" > ./env.sh

# sed replace as key=${BITBUCKET_ENV_VARIABLE:-default_value_from_example}
sed -i -E "s/^([A-Z_]+)=(.*)$/\1=\${\1:-\2}/g" ./env.sh

chmod +x ./build/env.sh

# Exec the env sh script and output content to .env file
./build/env.sh > ./build/.env

So in case you have defined in .env.example APP_NAME and also defined it in bitbucket Repository Variables the final .env will have key APP_NAME=value_of_bitbucket_variable

Related