How Google Cloud functions using Python to pull the credentials from Hashicorp Vault

Biswanath Giri
2 min readMay 13, 2023

Step-1

Create a new cloud function. You can do this in the Google Cloud Platform Console. Once you have created the function, you need to configure it to use the Python runtime. You can do this by clicking on the Runtime tab and selecting Python 3.7.

Step-2

You need to add the following imports to the top of your function:

import os
import requests
from urllib.parse import urlparse

def get_credentials(vault_url, secret_path):
"""Gets the credentials from Hashicorp Vault.

Args:
vault_url: The URL of the Hashicorp Vault server.
secret_path: The path to the secret in Vault.

Returns:
The credentials from Vault.
"""

# Create a request to Vault.
request = requests.get(
vault_url + secret_path,
headers={"X-Vault-Token": os.environ["VAULT_TOKEN"]}
)

# Check the status code of the request.
if request.status_code != 200:
raise ValueError("Error getting credentials from Vault: {}".format(request.status_code))

# Decode the response body.
response_body = request.content.decode("utf-8")

# Parse the JSON response body.
response = json.loads(response_body)

# Return the credentials.
return response["data"]

Step-3

You also need to create a variable to store the Hashicorp Vault URL. You can do this by setting the following environment variable:

export VAULT_URL=https://vault.example.com

Finally, you need to add a trigger to the function. You can do this by clicking on the Trigger tab and selecting HTTP.

Once you have configured the function, you can test it by clicking on the Test button. If the function works correctly, you should see the credentials from Hashicorp Vault in the output.

Here is an example of the output that you should see:

{
"access_token": "s.ABC123...",
"refresh_token": "r.DEF456...",
"id_token": "i.GHI789..."
}

--

--

Biswanath Giri

Helping students and professionals to learn cloud computing ,google cloud AI/ML and Google Workspace Helping Businesses with their journey to GCP