Sample 2: Spinning up Kubernetes clusters
I will start off with a personal note: when I first got into Kubernetes, it was probably the hardest thing in the world for me. I came from a development background and something like container orchestration was completely alien to me at the time. Kubernetes was born out of a very complicated need because of the rise in popularity of microservices. It was created to make life simpler for larger projects that were a mishmash of smaller projects. When it finally clicked for me, I realized how important Kubernetes was. It didn’t stop me from still being confused, though. So, I went to the coding well and it turns out there are a bunch of resources for guys like me. Once again, Python was a big help.
Creating a Kubernetes cluster usually involves using it in a cloud service. For this exercise, we are going to write code for setting up clusters in Google Cloud and Microsoft Azure:
from google.cloud import container_v1# Specify your project ID and cluster detailsproject_id = “<YOUR_PROJECT_ID>”zone = “<PREFERRED_ZONE>”cluster_name = “<YOUR_CLUSTER>”node_pool_name = ‘default-pool’node_count = 1 client = container_v1.ClusterManagerClient() # Create a GKE cluster cluster = container_v1.Cluster( name=cluster_name, initial_node_count=node_count, node_config=container_v1.NodeConfig( machine_type=’n1-standard-2’, ), ) operation = client.create_cluster(project_id, zone, cluster)
This operation will create a Kubernetes cluster in your Google Cloud project. Now let’s look at a way to do it in Azure:
from azure.mgmt.containerservice.models import ManagedCluster, ManagedClusterAgentPoolProfileresource_group = ‘<RESOURCE_GROUP_HERE>’cluster_name = ‘<CLUSTER_NAME_HERE>’location = ‘<LOCATION_HERE>’ agent_pool_profile = ManagedClusterAgentPoolProfile( name=’agentpool’, count=3, vm_size=’Standard_DS2_v2′,) aks_cluster = ManagedCluster(location=location, kubernetes_version=’1.21.0′, agent_pool_profiles = [agent_pool_profile])aks_client.managed_clusters.begin_create_or_update(resource_group, cluster_name, aks_cluster).result()
This creation code is fairly standard as well; it is simply a change in terminology. This is probably not the most efficient way to write code for this function (that will come later with Infrastructure as Code), but it gets the job done.
A lot of what we have looked at so far is gibberish to the layman, and sometimes the layman is the one most frequently operating resources. So let’s now look at a process that can be a blueprint for automating more complex processes to involve the layman more in the resource creation process.