Friday, April 24, 2020

How K8S authentication and authorization works in kubeadm?

To get started and practice a few things around K8S, I have setup a K8S cluster on my laptop as shown below using kubeadm. It gives me the utmost flexibility to try different things around K8S. A few days back I have posted a blog on how a K8S cluster gets bootstrapped. This gives an idea on how the different K8S process start and then we would be able to change some of the K8S process startup parameters to try out new features in K8S.

In the above K8S cluster, the default user (kubernetes-admin) created during the cluster setup has admin privileges to the cluster. This time I was curious on how the authentication and authorization work in K8S for this user to have full access to the cluster. This will enable me to be create additional users with different privileges, authentication and authorization mechanisms. It took me some time to get my mind/thoughts around it, but it's all interesting. This blog is all about the same.

Note that the cluster has been setup using kubeadm, for kops and other the below varies a little bit. And also, kubeadm cluster setup default used X509 certificates for authentication. Authentication Providers are not built into K8S and so has to be integrated with external systems like Google Accounts, Active Directory, LDAP etc.

1) By default with kubeadm installation, the user and cluster details are stored in the .kube/config file on the client side. This file helps kubectl command to connect and authenticate to the K8S cluster. The client-certificate-data and client-key-data fields in this file are used for authentication.

2) The X509 certificate from the .kube/config can be extracted and encoded. Finally the user details can be extracted with the opensll using the below commands. Note the output of the openssl command, the user name (CN) is kubernetes-admin and belongs to the system:masters organization (O).

grep "client-certificate-data" config | sed 's/    client-certificate-data: //g' > encoded.txt

base64 --decode encoded.txt > kubernetes-admin.crt

openssl x509 -noout -subject -in kubernetes-admin.crt

3) Now from a K8S cluster perspective. The cluster-admin (a ClusterRoleBinding object) binds the cluster-admin (a ClusterRole object with admin privilages) to the system:masters group. Any user of this group will have full cluster access.

kubectl describe cluster-admin

kubectl describe clusterrole cluster-admin

4) So, kubernetes-admin which belongs to the system:masters group as seen in the output of the openssl command has full access to the cluster.


K8S with the different concepts is a bit intimidating and it takes a bit of digging and research into the concepts to get a good understanding of the concepts. So, below is the mindmap for the above concept.

Note that (7 in the above diagram) maps the user details the organization name (system-masters) in the certificate with the group name (system-masters) in the ClusterRoleBinding. This is what gives the kubernetes-admin user full access to the K8S cluster.

As mentioned earlier, any user part of the system-masters group will have full access to the cluster.This Bitnami article (1) talks about the adding K8S user called 'employee' with X509 certificates. The same with some tweaks can be used to create another user besides the kubernetes-admin part of the system:master group.

Friday, April 10, 2020

MicroK8S - Easiest way to get started with K8S for those familiar with AWS

AWS provides different ways of running K8S in the Cloud via EKS, ECS and with/without Fargate. These are production ready setups for deploying K8S applications. In this blog we would look at microk8s, one of the most easiest way to get started with K8S. Here the assumption is that you already know how to create an EC2 instance and login to it.

Steps for setting up the K8S on EC2 using microk8s

-- Create an Ubuntu EC2 t2.micro instance with the default Security Groups. This Security Group allows all the traffic inbound and outbound. This is OK non-production purpose. Usually depending on the core services, add-ons installed the appropriate ports have to be opened in the Security Group.

-- Login to the EC2 via Putty or some other SSH client and execute the below commands.

#Install the microk8s. The latest release can be got from here.
sudo snap install microk8s --classic --channel=1.18/stable

#Create an alias in the .bashrc file
alias kubectl='microk8s kubectl'

#Add the user part of the microk8s group and change the ownership of the ~/.kube
#Exit and login back into the EC2 for these changes to take place into effect
sudo usermod -a -G microk8s $USER
sudo chown -f -R $USER ~/.kube

#check the status of the microk8s installation
microk8s status --wait-ready

-- Create a file deployment.yaml with the below content. Run 'kubectl create -f deployment.yaml' to create a Deployment with 3 Pods with the nginx Containers. BTW, kubectl is the CLI for interacting with K8S.

apiVersion: apps/v1
kind: Deployment
  name: nginx-deployment
    app: nginx
  replicas: 3
      app: nginx
        app: nginx
      - name: nginx
        image: nginx:1.14.2
        - containerPort: 80

-- 'kubectl get deployments' and 'kubectl get pods' will give the list of deployments and pods created in the above step.

--Now lets try to install the K8S Dashboard, which is a graphical way of interfacing with K8S. Execute the below commands in the EC2.

#Enable the K8S Dashboard
microk8s enable dashboard

#Get the token for the default user
token=$(kubectl -n kube-system get secret | grep default-token | cut -d " " -f1)
kubectl -n kube-system describe secret $token

#Port forward  the K8S Dashboard port 443 to port 10443 onto the EC2.
microk8s kubectl port-forward -n kube-system service/kubernetes-dashboard 10443:443 --address

-- Now the K8S Dashboard is ready to be accessed.

#Open the below URL in the browser. Note to replace the ec2-ip with the Public IP of the EC2.
#Provide the token got from the previous step
#The Deployments and Pods created earlier can be seen.


In the above setup a t2.micro instance was used which provides 1 vCPU and 1 GB of RAM. The only reason for using t2.micro is because it falls under the AWS Free Tier. Once the Deployment and Pods are started, the CPU is reaching the peak while some memory left is as shown below. With the t2.micro I have noticed that microk8s behaves a bit slow especially the Dashboard. Try to pickup a bigger instance for trying out various features of K8S.

The above steps are for creating a single node K8S cluster, multi node K8S cluster is also possible with microk8s as mentioned in the documentation here.

Setting up K8S with proper configuration especially for the Production setup is not an easy task. But, microk8s, K3S and Minikube have made it easy to get started with K8S.

Wednesday, April 8, 2020

How does the K8S cluster gets bootstrapped?

Although the different Cloud vendors provide managed service like AWS EKS, GCP GKE, Azure AKS and others, nothing beats running K8S on the local machine. Not only we can get started quickly, it's absolutely free and provides the ultimate freedom for any experimentation. Here is the setup I have using Oracle VirtualBox on Windows 10 OS.

It's a 3 node K8S cluster with one Control Plane node to do the orchestration and scheduling of the containers and two Worker nodes for the execution of the the containers. Recently, I upgraded to the latest version of K8S (1.18 as of this writing) and was able to try some of the new features.

The command 'kubectl get pods --all-namespaces -o wide' gives the Pods in all the namespaces. Below is the screenshot listing the Pods on the Control Plane and the Workers node. I was curious on how the Pods get started, this will give us a chance to check out the initialization parameters, tweak them and also to enable/disable features. This blog is all about the same. Note that the instructions are specific to installation using kubeadm and differ a bit for other installation process.

I was poking around in the K8S cluster and this StackOverflow Query (1) helped me. Below is the workflow on the how the K8S cluster gets bootstrapped. It all starts with the kubelet getting started automatically as a systemd service on all the Control Plane and the Workers nodes, which starts the minimum required static Pods for K8S to start working. Once the K8S Cluster boots up, additional Pods are started to get the K8S cluster into the desired state as stored in the etcd database.

Here is the workflow in a bit more detail

- Below is how the kubelet gets started as a systemd Service. /etc/systemd/system/kubelet.service.d/10-kubeadm.conf has the command to start the kubelet process and also the initialization parameters. Note that one of the parameter is /var/lib/kubelet/config.yaml location.

- In the /var/lib/kubelet/config.yaml file the staticPodPath variable is set to /etc/kubernetes/manifests path which has the yaml files for the static Pods to be started once the kubelet starts. As of now the apiserver, scheduler and etcd haven't started yet. So, kubelet starts them and manages them. Although these Pods are visible to the apiserver later, the apiserver doesn't manage them, kubelet is the one which manages them.

- In the /etc/kubernetes/manifests folder we have the yaml definitions for the etcd, apiserver, contoller-manager and the scheduler. These files will help us to understand how the K8S system Pods are initialized.

- OK, how about the coredns, flannel and proxy Pods getting started? The coredns and the proxy Pods are created by kubeadm during the K8S cluster initialization phase (1, 2) using kubeadm. The flannel Pods were created by me manually while setting up the K8S cluster (1). The details of these are stored in the etcd database as with any other user created K8S objects and K8S will automatically start them once the cluster starts.

Mystery solved, now that we know on how the K8S cluster gets bootstrapped, more can be explored. For using and administering K8S it is required to know the K8S bootstrap process in a bit more detail.

Tuesday, April 7, 2020

How does Key Pair work behind the scenes for Linux EC2 authentication?

Different  ways of authenticating against Linux EC2

Once a Linux EC2 instance has been created, the same can be accessed via Putty or some other SSH client. To access the EC2, first we need to authenticate the user. Either the Username/Password or the KeyPair can be used for authentication. There are pros and cons of each of them. AWS has chosen to go with the KeyPair way of authentication by default. If required this can be disabled and the Username/Password can be enabled.

How does KeyPair work behind the scenes for Linux EC2 authentication?

A picture conveys more than words, so is the above workflow. A KeyPair consists of a Private Key and a Public Key. The Private Key goes onto the Laptop and the Public Key automatically goes into the EC2 instance. Go through the above workflow to get to know what happens behind the scenes.

Note that the Private Key never leaves the laptop, this is one of the advantages of using the Key Pairs. Also, the way we never share the passwords with anyone, we should never share the Private Key with anyone. This would allow them to access the EC2. Also, the way we never use the same password across multiple services, never we should use the same Key Pair across multiple EC2 instances for the obvious reasons.

Also, it's always better to create a different set of Key Pairs for multiple users accessing the same EC2 instance, very similar to different passwords. Here is a small write-up from the AWS site on the same (1).

>> If you have several users that require access to a single instance, you can add user accounts to your instance. For more information, see Managing User Accounts on Your Linux Instance. You can create a key pair for each user, and add the public key information from each key pair to the .ssh/authorized_keys file for each user on your instance. You can then distribute the private key files to your users. That way, you do not have to distribute the same private key file that's used for the AWS account root user to multiple users.

Here are a few articles on some of the regularly performed tasks around the combination of EC2 and Key Pairs.

1) How do I enable a password login instead of a key pair when logging into my EC2 instance using SSH? (1, 2)

2) How do I add new user accounts with SSH access to my Amazon EC2 Linux instance? (1, 2)

3) Connecting to your Linux instance if you lose your private key (1)

4) Rotating the Key Pairs (1) - Note that there are many better ways, but this is the easiest.

There is lot more to Key Pairs and how the authentication works, but this article gives a basic gist on what happens BTS (behind the scenes) when we use KeyPairs to access an EC2 instance. I like to keep things clear and simple, this helps me to get my concepts clear and express myself better.

Monday, April 6, 2020

AWS AMI vs Launch Templates

Very often I get asked about the differences between AMI (Amazon Machine Images) and EC2 Launch Templates, although both of them have different purpose. This blog is about getting these concepts clear.

What is AMI?

There might be a requirement where we need to install softwares and applications on hundreds of EC2s. It's not practically possible to login to each of the EC2 and perform the task as it is time consuming and also prone to errors. We can automate these tasks using AMIs. Below is the workflow to start working with the AMIs.

Once an EC2 has been created, the appropriate software/applications have to be installed along with the configurations and then an AMI has to be created. The AMI has to OS and all the software/applications on top of it. The AMI usually is a couple of GB, based on the original EC2 which was created and is immutable (no changes can be made to it).

With this AMI, additional EC2s can be created and each one of the EC2 will have the original software automatically installed as in the case of Apache2. This makes getting the EC2 ready much easier/quicker.

Different ways of launching EC2 Instance

AWS provides multiple ways of launching EC2 instances via the SDK, CLI, CloudFormation and the EC2 Management Console (Web UI). From the EC2 Management Console again there are two ways, one is is using the Launch Instance wizard and other is via the EC2 Launch Templates as shown below.

Both these approaches lead to launching an EC2 and takes the required parameters for the same like the AMI which was mentioned above, the EBS volume size/type, SecurityGroup, KeyPair to be used and a few other details.

In the EC2 creation via the Wizard approach we need to select each and every time the AMI, Instance Type, Network Settings, Storage, Security Groups, pricing model etc from the different options. In the below screen the AMI has to be selected from the available ones. This is OK when we launch an EC2 a few times, but it's more of a routine task and is also time consuming.

This is where the EC2 Launch Templates come to the rescue. We can create a template and predefine all the EC2 properties and reuse the same to launch an EC2 instance. This way we don't need to select the EC2 properties again and again. Below is the template with the AMI, instance type, KeyPair, SecurityGroup predefined. Using this template we should be able to create an EC2 instance using Option (6).

CloudFormation Templates vs EC2 Launch Templates

While the EC2 Launch Templates can be used for the automation of the EC2 Instance creation. CloudFormation Templates are much more than that. It's possible to create many of the AWS resources via the CloudFormation Templates and connect them together, watch the drift (changes to the AWS resources) and much more. Here is the list of AWS Resources that can be created by CloudFormation.