Script the Registration of an SSH Target


How can I register an SSH target via the Octopus API? I’m not sure how to define the Display Name, Environment, Role, an existing Account (Key Pair), Host, Port, and Fingerprint. If you have a bash sample, that would be amazing, otherwise if you have a PowerShell sample, I will try to convert it to bash.

Hi Christopher,

I have this PowerShell script that should hopefully get you some ways to achieving your desired result:

$headers = @{"X-Octopus-ApiKey"="API-xxxxxxxxxxxxxxxxxxxxxxxxx"} 

$environments = Invoke-RestMethod "" -Headers $headers -Method Get
$theEnvironment = $environments | ? { $_.Name -eq "TheEnvironmentName" }

$accounts = Invoke-RestMethod "" -Headers $headers -Method Get
$theAccount = $accounts | ? { $_.Name -eq "TheAccount" }

$discovered = Invoke-RestMethod "" -Headers $headers -Method Get

#$discovered.Name = "MySshTargetName" # If you wanted to change the name of the deployment target (default is host name)
$discovered.Roles += "MyRole"
$discovered.EnvironmentIds += $theEnvironment.Id
$discovered.Endpoint.AccountId = $theAccount.Id

$discovered | ConvertTo-Json -Depth 10

Invoke-RestMethod "" -Headers $headers -Method Post -Body ($discovered | ConvertTo-Json -Depth 10)

I hope that helps!

Thank you and best regards,

Hi Christopher,

I’ve managed to dig up a bash script to add a new SSH target to Octopus as well, see below:

localIp=$(ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
fingerprint=$(ssh-keygen -lf /etc/ssh/ | cut -d' ' -f2 | awk '{ print $1}')

environmentId=$(wget --header="X-Octopus-ApiKey: $apiKey" -O- ${serverUrl}/api/environments | jq ".Items[] | select(.Name==\"${environment}\") | .Id" -r)

machineId=$(wget --header="X-Octopus-ApiKey: $apiKey" --post-data "{\"Endpoint\": \"CommunicationStyle\":\"Ssh\",\"AccountId\":\"$accountId\",\"Host\":\"$localip\",\"Port\":\"22\",\"Fingerprint\":\"$fingerprint\"},\"EnvironmentIds\":[\"$environmentId\"],\"Name\":\"$machineName\",\"Roles\":[\"linux\"]}" -O- ${serverUrl}/api/machines | jq ".Id" -r)
  echo Added machine \"$machineName\" '('$machineId') - Launching health check task'
  wget --header="X-Octopus-ApiKey: $apiKey" --post-data "{\"Name\":\"Health\",\"Description\":\"Check $machineName health\",\"Arguments\":{\"Timeout\":\"00:05:00\",\"MachineIds\":[\"$machineId\"]}}" -O-  ${serverUrl}/api/tasks | jq ".Id" -r

I hope that helps you some more.

Thank you and best regards,

It sure does. Thank you very much.