Python to Bootstrap OpenShift Gitops

Here’s a python script to bootstrap OpenShift gitops in a fresh cluster. I like this one a bit better because I think python is easier to code and debug.

#!/usr/bin/env python3

from kubernetes import client, config
import time

def install_gitops_operator():
    # Load the kubeconfig
    try:
        # Try to load from default location or from service account if running in-cluster
        config.load_kube_config()
        print("Loaded kubeconfig from default location")
    except:
        try:
            # Try in-cluster config if running in a pod
            config.load_incluster_config()
            print("Loaded in-cluster config")
        except:
            print("Failed to load kubeconfig or in-cluster config")
            return False

    # Create API clients
    custom_api = client.CustomObjectsApi()

    # Define the GitOps operator subscription
    subscription = {
        "apiVersion": "operators.coreos.com/v1alpha1",
        "kind": "Subscription",
        "metadata": {
            "name": "openshift-gitops-operator-subscription",
            "namespace": "openshift-operators"
        },
        "spec": {
            "channel": "latest",
            "installPlanApproval": "Automatic",
            "name": "openshift-gitops-operator",
            "source": "redhat-operators",
            "sourceNamespace": "openshift-marketplace"
        }
    }

    # Create the subscription
    try:
        custom_api.create_namespaced_custom_object(
            group="operators.coreos.com",
            version="v1alpha1",
            namespace="openshift-operators",
            plural="subscriptions",
            body=subscription
        )
        print("Created GitOps operator subscription")
    except client.exceptions.ApiException as e:
        if e.status == 409:
            print("Subscription already exists, continuing...")
        else:
            print(f"Error creating subscription: {e}")
            return False

    # Wait for the operator to be installed
    print("Waiting for OpenShift GitOps operator to be installed...")
    retries = 20
    for i in range(retries):
        try:
            # Check if the CSV is installed
            csvs = custom_api.list_namespaced_custom_object(
                group="operators.coreos.com",
                version="v1alpha1",
                namespace="openshift-operators",
                plural="clusterserviceversions"
            )
            
            for csv in csvs['items']:
                if "openshift-gitops-operator" in csv['metadata']['name']:
                    if csv['status']['phase'] == 'Succeeded':
                        print(f"OpenShift GitOps operator installed successfully: {csv['metadata']['name']}")
                        return True
                    else:
                        print(f"Operator installation in progress: {csv['status']['phase']}")
        except Exception as e:
            print(f"Error checking installation status: {e}")
        
        time.sleep(15)
        print(f"Checking again... ({i+1}/{retries})")
    
    print("Timed out waiting for operator installation")
    return False

def verify_gitops_components():
    # Load Kubernetes configuration
    try:
        config.load_kube_config()
    except:
        try:
            config.load_incluster_config()
        except:
            print("Failed to load kubeconfig or in-cluster config")
            return False

    # Create the core API client
    v1 = client.CoreV1Api()

    # Wait for GitOps namespace to be created
    print("Waiting for openshift-gitops namespace to be created...")
    retries = 10
    namespace_created = False
    
    for i in range(retries):
        try:
            namespaces = v1.list_namespace()
            for ns in namespaces.items:
                if ns.metadata.name == "openshift-gitops":
                    namespace_created = True
                    print("openshift-gitops namespace is created")
                    break
            
            if namespace_created:
                break
                
        except Exception as e:
            print(f"Error checking namespaces: {e}")
        
        time.sleep(10)
        print(f"Checking again... ({i+1}/{retries})")
    
    if not namespace_created:
        print("Timed out waiting for openshift-gitops namespace")
        return False
    
    # Wait for pods to be running
    print("Waiting for GitOps pods to be running...")
    retries = 20
    for i in range(retries):
        try:
            pods = v1.list_namespaced_pod(namespace="openshift-gitops")
            running_pods = 0
            total_pods = len(pods.items)
            
            if total_pods == 0:
                print("No pods found yet in openshift-gitops namespace")
            else:
                for pod in pods.items:
                    if pod.status.phase == "Running":
                        running_pods += 1
                
                print(f"{running_pods}/{total_pods} pods are running")
                
                if running_pods == total_pods and total_pods > 0:
                    print("All GitOps pods are running")
                    return True
        except Exception as e:
            print(f"Error checking pods: {e}")
        
        time.sleep(15)
        print(f"Checking again... ({i+1}/{retries})")
    
    print("Timed out waiting for GitOps pods to be running")
    return False

if __name__ == "__main__":
    print("Starting OpenShift GitOps operator installation...")
    if install_gitops_operator():
        print("OpenShift GitOps operator installed successfully")
        print("Verifying GitOps components...")
        if verify_gitops_components():
            print("GitOps components are running")
            print("Installation completed successfully!")
        else:
            print("Some GitOps components are not running yet")
    else:
        print("Failed to install OpenShift GitOps operator")

One comment

Comments are closed.