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

1.7k views Asked by At

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

1

There are 1 answers

0
Matt Kornfield On

You'll most likely want to use the RbacAuthorizationV1Api. Afterward you can call create_namespaced_role and create_namespaced_role_binding to make what you need.

A snippet might look like

from kubernetes import client, config

config.load_incluster_config()
policy_api = client.RbacAuthorizationV1Api()
role = client.V1Role(
    metadata=client.V1ObjectMeta(name="my-role"),
    rules=[client.V1PolicyRule([""], resources=["pods"], verbs=["get", "list"])],
)
policy_api.create_namespaced_role(namespace="my-namespace", body=role)

role_binding = client.V1RoleBinding(
    metadata=client.V1ObjectMeta(namespace="my-namespace", name="my-role-binding"),
    subjects=[
        client.V1Subject(
            name="user", kind="User", api_group="rbac.authorization.k8s.io"
        )
    ],
    role_ref=client.V1RoleRef(
        api_group="rbac.authorization.k8s.io", kind="Role", name="user-role"
    ),
)
policy_api.create_namespaced_role_binding(namespace="my-namespace", body=role_binding)

Some more useful examples here.