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)
witheval $(echo sleep 100)
, I find that the sleep process is owned by user ubuntu, not root.