Using SSH Key as variable for a runbook

Greetings.

I have a requirement for connecting via SSH to an instance by the tentacle that is in the same private subnet. To achieve this, we have an SSH Private Key that we want to use as a variable in the runbook or, if possible, use the key defined in the infrastructure accounts. The problem here is that when we want to use the SSH Key in the variable, we validate it with key-gen and it says that the resulting file isn’t a key :frowning_face:

This is the script that we are using for now
´´´
#!bin/bash
echo “$(get_octopusvariable “SSH-Key”)” > devops-ssh-key.pem
cat devops-ssh-key.pem
chmod 600 devops-ssh-key.pem
ssh-keygen -l -f devops-ssh-key.pem
ssh -tt -vvv -i devops-ssh-key.pem user@xxx.xxx.xxx.xxx
touch it-works.txt
´´´

Hi @andres.carcamo,

Thank you for reaching out, and I’m sorry you are having trouble in using the SSH command via this runbook.

In my testing, I was able to replicate and resolve this issue by reformatting your script to the following:

#!bin/bash
sshKey=$(get_octopusvariable "SSH-Key")
echo "-----BEGIN RSA PRIVATE KEY-----" > devops-ssh-key.pem
echo $sshKey >> devops-ssh-key.pem
echo "-----END RSA PRIVATE KEY-----" >> devops-ssh-key.pem
chmod 400 devops-ssh-key.pem
ssh -i devops-ssh-key.pem user@<REMOTE_SERVER_IP> "touch it-works.txt"

The issue appears to be with the BEGIN and END statements, as this file needs to be formatted in a specific way to be read by the SSH process. Note that I prepended and appended these lines within my script, and then I made sure to remove these lines from the sensitive variable itself.

After making these changes, my runbook ran successfully and I was able to verify that the “it-works.txt” file existed on my remote Linux server.

I don’t know if this will be an issue for you, but if you run into any errors related to needing to accept the remote server’s fingerprint when connecting the first time then you may need to add this line to your script (or a variation of it), where the placeholder value “<REMOTE_SERVER_IP>” should be the Linux server you are trying to connect to in your script :

ssh-keyscan -H <REMOTE_SERVER_IP> >> ~/.ssh/known_hosts

This command will append the remote server’s host key information to the local “known_hosts” file, bypassing the need to do this interactively.

I hope this helps, but feel free to reach out if you need any more assistance.

Best regards,

Britton

This topic was automatically closed 31 days after the last reply. New replies are no longer allowed.