Unable to load environment variables from file over ssh

I running following command:

ssh -i ${SSH_KEY_PATH} ${SSH_SERVER_URI} "export $(grep -v '^#' /home/ubuntu/code/.env.prod | xargs -d '\n') && aws ecr get-login --region eu-central-1"

and getting following error:

Unable to locate credentials. You can configure credentials by running "aws configure".

Looks like env variables are not accessible. How to load then so that I can login to aws via AWS CLI?


Solution 1:

Why It Broke

When you put $(...) inside a double-quoted string, it's run while that string is being evaluated, which is before ssh starts. Consequently, the grep command runs on your local machine, which presumably doesn't have the file in question (or at least, doesn't have the same contents as the remote copy).

How To Avoid The Problem

You don't need $(...) or xargs or export at all. Use set -a to make all variables be automatically exported, then source your file, with set +a used to turn auto-export back off when done:

ssh -i "$SSH_KEY_PATH" "$SSH_SERVER_URI" \
  'set -a; . /home/ubuntu/code/.env.prod; aws ecr get-login --region eu-central-1'