1

As part of an Upstart script, I need to launch ssh-agent to load a GitHub deployment key, so in the script I have:

eval "$(ssh-agent -s)"
ssh-add $HOME/.ssh/id_rsa

The problem is that when the service is restarted, ssh-agent is relaunched, leaving me with multiple copies running. I'm pretty sure it's because the environment variables are lost when the script is re-run. I tried the following:

script
    ...
    # Ensure SSH agent is running
    if [ -z "$SSH_AUTH_SOCK" ]; then
            eval "$(ssh-agent -s)" >/dev/null
            ssh-add $HOME/.ssh/id_rsa
            initctl set-env --global SSH_AUTH_SOCK=$SSH_AUTH_SOCK
            initctl set-env --global SSH_AGENT_PID=$SSH_AGENT_PID
            initctl set-env --global SSH_AGENT_LAUNCHER=upstart
    fi

exec ...
...
end script

post-stop script

    # Shut down SSH agent
    if [ "$SSH_AGENT_LAUNCHER" = upstart ]; then
            kill $SSH_AGENT_PID 2>/dev/null || true
            initctl unset-env --global SSH_AUTH_SOCK
            initctl unset-env --global SSH_AGENT_PID
            initctl unset-env --global SSH_AGENT_LAUNCHER
    fi

end script

The issue here is that I have a setuid in the script, so the initctl call isn't allowed, as the user doesn't have the required privileges. Is there an easy way to export the environment variables from the script so that they are available in the post-stop script, or is writing them to a file and sourcing that file in post-stop the best way to do it?

1 Answers1

0

I ended up splitting the ssh-agent launch into a one off task that starts at startup and exports the path to the agent settings (now stored in a file), so that other startup scripts can just depend on the ssh-agent startup script and source the file to retrieve the environment variables.