This is how I solved it for GCP Cloud Functions. First I used Python to print out a base64 encoded key of my key file 'temp_key.pem'. The reason I did this was because copying and pasting the key didn't work in the GCP environment variables even though it did locally:
import base64
with open('temp_key.pem', 'rb') as f:
blob = base64.b64encode(f.read())
print(blob)
for_google_cloud_function = blob.decode('utf-8')
print(for_google_cloud_function)
The output of this I used an my environment variable SSH_KEY_BLOB. In my GCP Cloud Function I then added this (I've missed out the line getting it from the GCP environment variables):
# decode key back into a useable form from base64
SSH_KEY_BLOB_DECODED = base64.b64decode(SSH_KEY_BLOB)
SSH_KEY = SSH_KEY_BLOB_DECODED.decode('utf-8')
# pass key to parmiko to get your pkey
pkey = paramiko.RSAKey.from_private_key(io.StringIO(SSH_KEY))
# setup your SSHTunnel like normal
server = SSHTunnelForwarder(
remote_server_ip,
ssh_username=SSH_USERNAME,
ssh_pkey=pkey,
remote_bind_address=('127.0.0.1', 27017)
)
That way the key is not hard coded and the function is self sufficient from the file. They may be better ways but this worked for me.