Introduction: Why Automate OpenShift OAuth Token Retrieval in Python?
If you’re working with OpenShift APIs, automating token retrieval is a must. In this post, I’ll show you how to use Python to securely retrieve an OpenShift OAuth token. This method is ideal for DevOps workflows, CI/CD pipelines, and infrastructure automation — especially when using self-signed certificates
Prerequisites for OpenShift OAuth Token Python Script
Before running the script, make sure you have:
- Python 3.x installed
- The
requests
library (pip install requests
) - A self-signed certificate file named
cert.pem
in the same directory - Environment variables
USER_NAME
andPASSWORD
set with your OpenShift credentials
export USER_NAME=your_username export PASSWORD=your_password
How the OpenShift OAuth Token Python Function Works
The function get_token()
performs the following:
- Constructs the OpenShift OAuth URL
- Retrieves credentials from environment variables
- Loads the self-signed certificate
- Sends a GET request to the OAuth endpoint
- Extracts the token from the redirect URL
Here’s the full code:
import requests import os def get_token(): """Function to retrieve the token from the OpenShift Cluster""" cluster_url = "https://oauth-openshift.apps.openshift.example.com" username = os.environ["USER_NAME"] password = os.environ["PASSWORD"] cert_path = os.path.join(os.path.dirname(__file__), "cert.pem") response = requests.get( f"{cluster_url}/oauth/authorize?client_id=openshift-challenging-client&response_type=token", auth=(username, password), timeout=15, verify=cert_path, allow_redirects=True ) token = response.url.split("access_token=")[1].split("&")[0] return token token = get_token() print(token)
Video: OpenShift OAuth Token Python Tutorial
This video demonstrates how to set up your environment, run the script, and securely retrieve the token.
Related Techniques
If you’re looking for alternative methods or deeper OAuth insights:
- OpenShift – get a login token w/out accessing the web console shows how to retrieve tokens using curl and manual API calls.
- OpenShift 4 OAuth Identity Providers dives into configuring identity providers for OpenShift clusters.
🛡️ Security Tips
- Never expose your OAuth token in logs or public output.
- Use environment variables or secret managers to store credentials.
- Rotate tokens regularly and monitor access patterns.
GitHub Repository
You can find the full source code and README on GitHub – iwindon/openshift-auth.
Discover more from The Root User
Subscribe to get the latest posts sent to your email.