Retrieve OpenShift OAuth Token with Python

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 and PASSWORD 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:

  1. Constructs the OpenShift OAuth URL
  2. Retrieves credentials from environment variables
  3. Loads the self-signed certificate
  4. Sends a GET request to the OAuth endpoint
  5. 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.

If you’re looking for alternative methods or deeper OAuth insights:

🛡️ 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.

Share

Ivan Windon

Ivan Windon is a Senior Linux Administrator at Metric5. Ivan is actively engaged in Cloud Technologies with Oracle Gov Cloud, and Azure. Ivan has extensive experience with Linux and Windows administration, DNS, Networking, IDM, and Security. In his free time, he enjoys being with his wife and two children.

You may also like...

Leave a Reply