Sunday, October 9, 2022

Working with Kubernetes using Python - Part 06 - Create namespace

Following code snipet uses Python client for the kubernetes API to create namespace. You will need to specify the kubeconfig file and the context to use for creating the namespace. This is an example case if you are working with multiple kubeconfig files where multiple K8s clusters could be present in each kubeconfig file.

from kubernetes import client, config
import argparse


def load_kubeconfig(kubeconfig_file, context_name):
try:
config.load_kube_config(
config_file=f"{kubeconfig_file}", context=f"{context_name}"
)
except config.ConfigException as err:
print(err)
raise Exception("Could not configure kubernetes python client!")
v1 = client.CoreV1Api()
return v1


def create_ns(v1, ns_name):
print("Creating namespace")
namespace = client.V1Namespace(metadata={"name": ns_name})
ret = v1.create_namespace(namespace)
print(ret)


def main():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--context", required=True, help="K8s context")
parser.add_argument("-f", "--file", required=True, help="Kubeconfig file")
args = parser.parse_args()

context = args.context

v1 = load_kubeconfig(args.file, context)

ns_name = input("Enter namespace name: ")
create_ns(v1, ns_name)


if __name__ == "__main__":
main()

Following is sample output:

❯ python3 create_namespace.py -c tkc-admin@tkc -f /Users/vineethac/testing/ccs/tkc.kubeconfig
Enter namespace name: vineethac-test11
Creating namespace
{'api_version': 'v1',
'kind': 'Namespace',
'metadata': {'annotations': None,
'cluster_name': None,
'creation_timestamp': datetime.datetime(2022, 12, 7, 11, 57, 17, tzinfo=tzutc()),
'deletion_grace_period_seconds': None,
'deletion_timestamp': None,
'finalizers': None,
'generate_name': None,
'generation': None,
'labels': {'kubernetes.io/metadata.name': 'vineetha-test11'},
'managed_fields': [{'api_version': 'v1',
'fields_type': 'FieldsV1',
'fields_v1': {'f:metadata': {'f:labels': {'.': {},
'f:kubernetes.io/metadata.name': {}}}},
'manager': 'OpenAPI-Generator',
'operation': 'Update',
'time': datetime.datetime(2022, 12, 7, 11, 57, 17, tzinfo=tzutc())}],
'name': 'vineethac-test11',
'namespace': None,
'owner_references': None,
'resource_version': '5518430',
'self_link': None,
'uid': '0e9f1211-e09f-4d2d-b475-8995bb0c0907'},
'spec': {'finalizers': ['kubernetes']},
'status': {'conditions': None, 'phase': 'Active'}}