How to pass environment variables to ssh deploy job?

I have defined a env variable named GRPC_ADDR in CircleCI under the project settings. I want to use this variable while deploying with my app on a server using ssh. I use docker-compose to orchestrate my containers and docker-compose depends on the GRPC_ADDR. However, when the job executes docker-compose can seem to find the env variable. Here is my CircleCI config:

jobs:
    deploy:
        machine: true
        steps:
            - add_ssh_keys:
                  fingerprints:
                    - #fingerprint here
            - run:
                name: Setup Environment Variables
                command: |
                        echo "export GRPC_ADDR=$GRPC_ADDR" >> $BASH_ENV
            - run:
                  name: Deploy over SSH
                  command: |
                      ssh $SSH_USER@$SERVER bash << EOF
                       
                        cd example-dir
                        
                        docker-compose stop; # stop the containers if they are runnning
                        docker-compose up -d --build; #docker-compose can't find env variable here
                      EOF
workflows:
    version: 2
    build_and_deploy:
        jobs:
            - deploy

docker-compose gives me this warning as it can’t find the env variable The GRPC_ADDR variable is not set. Defaulting to a blank string. . This leads my deployment to fail as that env variable is required.

So, how can I fix this issue?

Thanks in advance.

Hello! Can you try echo “export GRPC_ADDR=$GRPC_ADDR” >> $GRPC_ADDR

@jkzilla After trying your suggestion, CircleCI is now failing with the following error:

#!/bin/bash -eo pipefail

“export GRPC_ADDR=$GRPC_ADDR” >> $GRPC_ADDR

/bin/bash: ********************************: No such file or directory

Exited with code 1

@habush It looks like the GRPC_ADDR variable is returning undefined on the server itself since that is where the Docker commands are being executed. You’ll need to define those on the server-side, rather than in your job :slight_smile:

1 Like

You’re issue is that you’re SSH’ing to a new host and that host doesn’t have your CircleCI environment (as you’re probably discovered)

One solution is to copy your environment over and source it on the target machine. eg
SCP $BASH_ENV $SSH_USER@$SERVER:circleci.env
Then update your script to source the circleci.env at the start and remove it at the end.
eg

 ssh $SSH_USER@$SERVER bash << EOF
                       source circleci.env
                        cd example-dir
                        .....
                        rm ~/circleci.env
                  EOF

A slightly safer way that follows the same approach is to change the echo "export line above to be a local file rather than $BASH_ENV and copy that file instead of $BASH_ENV

There are multiple other approaches in https://superuser.com/questions/48783/how-can-i-pass-an-environment-variable-through-an-ssh-command.