0

I'm using the following script to bootstrap my AWS EC2 instances after launch. It runs without errors when I execute it manually after ssh-ing into the instance.

#!/bin/bash

set -eu
eval $(ssh-agent -s)
ssh-add ~/.ssh/my_github_deploy_key
git clone git@github.com:myOrg/myProject.git
eval $(ssh-agent -k)

After learning about the userdata feature in AWS EC2, I decided to use them. A userdata script is run automatically by AWS when an EC2 instance first boots.

userdata scripts are run as the root user, while I want my project folder to be owned by a non-root user, so I modified my script like this:

#!/bin/bash

runuser -u ubuntu bash << EOF
set -eu
eval $(ssh-agent -s)
ssh-add ~/.ssh/fotobot_deploy_key
git clone git@github.com:fotobot/api.git fotobotFacRegPoller
eval $(ssh-agent -k)
EOF

AWS reports that my userdata script fails with the error Error connecting to agent: Permission denied when executing the ssh-add instruction. I found that the ssh-agent process started on the previous instruction is owned by root instead of user ubuntu, and suspect this is the cause.

Why is ssh-agent owned by root instead of user ubuntu?


Additional info:

  • When I replace eval $(ssh-agent -s) with eval $(echo sleep 100), I find that the sleep process is owned by user ubuntu, not root.
ack_inc
  • 1,015
  • 7
  • 13
  • 1
    The `$(...)` command substitutions are evaluated by the root shell (and therefore `ssh-agent` is executed by root) before the here-document is passed to `runuser`. You need to either quote (or escape) the here-doc delimiter (like `... << 'EOF'`), or escape the `$` characters inside the here-document. See ["How to `cat <>` a file containing code?"](https://stackoverflow.com/questions/22697688/how-to-cat-eof-a-file-containing-code) and ["Disable command substitution in heredoc?"](https://stackoverflow.com/questions/65899041/disable-command-substitution-in-heredoc) – Gordon Davisson Aug 04 '23 at 10:09

0 Answers0