'How to write/use K8 Python client to create a new role, sa & role binding

I am currently figuring out what is the best way to programmatically manage the Kubernetes cluster (eks). I have come across a python Kubernetes client where I was able to load the local config and then create a namespace.

I am running a jenkins job where I would like it to create a namespace, role, rolebinding, as. I have managed to create the namespace however having trouble understanding on how to call the function to create a new role, new role binding.

Here is the snippet to create namespaces using k8 python client:

from kubernetes import dynamic, config
from kubernetes import client as k8s_client
from kubernetes.client import api_client
import time, sys

def create_namespace(namespace_api, name):
    namespace_manifest = {
        "apiVersion": "v1",
        "kind": "Namespace",
        "metadata": {"name": name, "resourceversion": "v1"},
    }
    namespace_api.create(body=namespace_manifest)


def delete_namespace(namespace_api, name):
    namespace_api.delete(name=name)


def main():
    # Load local config
    
    client = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_incluster_config())
    )

    namespace_api = client.resources.get(api_version="v1", kind="Namespace")


    # Creating a namespace

    namespace_name = sys.argv[1]
    create_namespace(namespace_api, namespace_name)
    time.sleep(4)

    print("\n[INFO] namespace: " + namespace_name + " created")


if __name__ == '__main__':
    main()

I would appreciate any support



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source