A Quick Script To Connect To An OCI Bastion Service

A Quick Script To Connect To An OCI Bastion Service

Here is a little script I knocked together to make it easier and quicker to connect to an Oracle OCI SSH Bastion service. Why use GUI when you can script it?


First, the script checks if you already have an active bastion session, titled after your OS user. If not, it will create a new session for you and then wait 2 minutes before attempting to connect to it.


The details of the instance you connect to, via the bastion service, is defined in a file called `instance.json`

bastion.sh

#!/bin/zsh

#Exit on error
set -e

SLEEP=120

BASTION=ocid1.bastion.oc1.uk-london-1.verylongstring
REGION="uk-london-1"

#SSH_PUB_KEY="/Users/${USER}/SSH/bastion.pub"
SSH_PUB_KEY="/Users/${USER}/.ssh/id_rsa.pub"

# for some reason, the session gets created with first letter upper-case.
SESS_NAME=${(C)USER}

get_session_ocid() {
	SESS_OCID=$(oci bastion session list --bastion-id ${BASTION} --session-lifecycle-state ACTIVE --display-name ${SESS_NAME} --all  | jq -r '.data[] | .id')
}

#Do we already have an active session in the Bastion service
get_session_ocid

if [ -z "${SESS_OCID}" ]; then
	echo "We need to create a new session"
	SESS_OCID=$(oci  bastion session create --bastion-id ${BASTION} --target-resource-details file://instance.json --display-name ${SESS_NAME} --ssh-public-key-file $SSH_PUB_KEY | jq -r '.data.id')
	echo "Created a new session: ${SESS_OCID}"
	echo "It takes a moment to start the new session, so we will nap for ${SLEEP} seconds"
	sleep ${SLEEP}
	get_session_ocid
	if [ -z "$SESS_OCID" ]; then
		echo "Might be it took a bit longer than we thought. Try again in a moment."
		exit 1
	fi
else
	echo "Found active session: "
fi

IP=$(jq -r '.targetResourcePrivateIpAddress' bast.json)

ssh -o ProxyCommand="ssh -W %h:%p -p 22 [email protected].${REGION}.oci.oraclecloud.com" opc@${IP} #Add your port forward etc here

And the JSON

  {
    "sessionType": "MANAGED_SSH",
    "targetResourceId": "ocid1.instance.oc1.uk-london-1.verylongstring",
    "targetResourceOperatingSystemUserName": "opc",
    "targetResourcePort": 22,
    "targetResourcePrivateIpAddress": "10.0.1.300"
  }


and now we can connect

./bastion.sh
We need to create a new session
Created a new session: ocid1.bastionsession.oc1.uk-london-1.verylongstring
It takes a moment to start the new session, so we will nap for 120 seconds
Activate the web console with: systemctl enable --now cockpit.socketLast login: Mon Oct  2 12:46:15 2023 from 10.0.0.400
[opc@bastionhost ~]$