Monday, 18 April 2022

CKA Kubernetes ( K8S ) Linux Networking Cheat sheet

The preparation for the CKA (Certified Kubernetes Administrator) requires lots of practice and practice. Fortunately, we have lots of online playgrounds to keep practicing, there are lots of free courseware available and lots of paid as well are available. In addition to that, we get two attempts to clear the exam


It is good to have some basic understanding of Linux networking concepts and commands as in the CKA exam we will be asked to solve the network related issue

• To get the physical Ethernet available
○ ip link
○ ip addr
• To add an IP address to a interface
○ ip addr add 192.168.1.11/24 dev <ens3>
• To get the list of IP routing tables
○ route
○ ip route
• To add a routing to target via a gateway
○ ip route add <192.168.2.0/24> via <192.168.1.1>
§ 192.168.1.1 - is the IP address where the 'Router' is connected to the network and acts like a gateway 
§ 192.168.2.0/24 - is the CIDR of the target network
• To forward traffic/packets from one interface to another interface in the router or gateway
○ Edit /proc/sys/net/ipv4/ip_forward
§ Set the value to '1' but this will not be preserved on reboots
○  Edit /etc/sysctl.conf --> add an entry 'net.ipv4.ip_forward=1'
§ This change will be preserved on reboots
• To know which DNS server our machine is talking to
○ /etc/resolv.conf
§ We can have multiple nameservers defined
§ Add entry like 'nameserver 8.8.8.8' to point to a public DNS server hosted by google
• Search domain
○ We can specify the domain name that we want to append with user given URL
○ An entry like below in /etc/resolv.conf solves this
§ 'search mycompany.com'
• The order to resolve when duplicate entries are seen in local /etc/hosts and in DNS server
○ /etc/nsswitch.conf
§ Add entry like 'hosts:          files dns' --> Here the first preference goes to local /etc/hosts and then to DNS
• To test DNS resolution
○ nslookup www.google.com
§ nslookup will not consider the entries in /etc/hosts file
○ dig www.google.com
§ This will give more details
• Network namespaces
○ ip netns add <red>
§ For creating the namespaces
○ ip netns
§ for listing the namespaces
○ ip netns exec <red> ip link
OR
○ ip -n <red> ip link
§ For executing commands inside namespaces
• Address Resolution Protocol (ARP) table
○ arp
○ ip netns exec red arp
• Virtual Ethernet
○ ip link add <veth-red> type veth
§ For creating a virtual ethernet
○ ip link add <veth-blue> type veth peer name <veth-red>
○ ip link set veth-blue netns blue
§ For assigning the veth to a namespace
○ ip -n red link del veth-red
• Assigning IP addresses for virtual ethernet interfaces
○ ip -n <red> addr add 192.168.15.1 dev <veth-red>
○ ip -n <red> link set veth-red up
• Virtual Bridge
○ ip link add v-net-0 type bridge
§ This will acts like a virtual switch where the network namespaces can connect to
• netstat -nptl
○ To know the list of process and in which port it is listening to
• netstat -anp
○ To know the list of active connection etc
• iptables -L -t net | grep db-service
• host web-service

Will print the Fully Qualified Domain Name (FQDN) where it is accessible from


CKA Kubernetes ( K8S ) Command Cheat sheet

The preparation for the CKA (Certified Kubernetes Administrator) requires lots of practice and practice. Fortunately, we have lots of online playgrounds to keep practicing, there are lots of free courseware available and lots of paid as well are available. In addition to that, we get two attempts to clear the exam



Command Cheatsheet


• Create
○ kubectl run nginx --image=nginx
○ kubectl create deployment nginx --image=nginx --dry-run -o yaml
○ kubectl create deployment nginx --image=nginx --replicas=4
○ kubectl expose pod redis --name=redis-service --port=8080
○ kubectl create service clusterip redis --tcp=6379:6379
• Update
○ kubectl scale deployment nginx --replicas=5
○ kubectl scale --replica=5 replicaset/my-replicaset
• Read
○ kubectl get all
○ kubectl get pods --selector env=dev
○ kubectl get pods -l name=internal
○ kubectl get pods --show-labels
○ kubectl get pod webapp -o yaml > webapp-pod.yaml
○ kubectl get deployments.apps
○ kubectl get nodes -o json
○ kubectl get nodes -o=jsonpath='{.items[*].metadata.name}'
○ kubectl get nodes -o=custom-columns=NODE:.metadata.name,CPU:.status.capacity.cpu
• Node Related
○ Taint and Tolerance
§ kubectl taint nodes node01 app=blue:NoSchedule
§ kubectl describe node node01 | grep Taints
○ Label
§ kubectl label nodes node01 size=large
○ Upgrades
§ kubectl drain node01
§ kubectl cordon node01
§ kubectl uncordon node01
○ Events
§ kubectl get events
§ kubectl get events -o wide
• Namespaces
○ kubectl create namespace dev
○ kubectl config set-context $(kubectl config current-context) --namespace = dev
○ kubectl get pods --all-namespaces
• DaemonSet
○ kubectl get daemonsets
• Events
○ kubectl get events
• Monitoring 
○ kubectl top node
○ kubectl top pod
○ kubectl logs -f <pod-name> <container-name>
○ kubectl logs -f --previous  <pod-name> <container-name>
§ helpful when the pod are getting restarted and wanted to see the previous pod log
• Application Lifecycle
○ kubectl rollout status deployment/my-deployment
○ kubectl rollout history deployment/my-deployment
○ kubectl rollout undo deployment/my-deployement
• To get the sample definition
○ kubectl explain pods --recursive 
• Maintenance
○ kubeadm upgrade plan
○ apt-get upgrade -y kubeadm=1.12.0-00 
○ kubeadm upgrade apply v1.12.0  (First we should install v1.12.0 kubeadm)
○ apt-get upgrade -y kubelet=1.12.0-00
○ systemctl restart kubelet
○ kubeadm upgrade node config --kubelet-version v1.12.0
• Backup
○ kubectl get all --all-namespaces -o yaml > all-deploy-services.yaml
• Certificates creations
○ openssl genrsa -out ca.key 2048   => For creating private key
○ openssl req -new -key ca.key -subj "/CN=KUBERNETES-CA" -out ca.csr   => For creating a CSR or Certificate Signing Request file
○ openssl x509 -req -in ca.csr -signkey ca.key -out ca.crt => For creating the signed certificate, for CA we use the its own private key for signing the certificate
○ openssl x509 -in apiserver.crt -text -noout => for viewing the certificate details
• Certificate APIs
○ kubectl get csr 
○ kubectl certificate approve jane
○ kubectl get csr jane -o yaml
• kubeconfig
○ kubectl config view
○ kubectl config use-context prod
• Authorization
○ kubectl auth can-i create deployments
○ kubectl auth can-i create deployments --as dev-user
• List of all the resource type in K8S
○ kubectl api-resources --namespaced=true
○ kubectl api-resources --namespaced=false   (This will return cluster scoped resources)

References

https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands


Tuesday, 15 March 2022

ATP Datapump using resource principal authentication for non admin user

 The Datapump concept in Oracle database is very much useful for different usecases like taking backup, migrating the database from on-prem to cloud and more. Another advantage is it can directly push the dump into the OCI Object Storage  

https://docs.oracle.com/en/cloud/paas/autonomous-database/adbsa/export-data-create-dump-file.html#GUID-8D734C1A-FAF3-446C-B777-16DF62FB049E

If we want to upload the dump into OCI object storage, we can use different authentication mechanism like authToken, basic credential based authentication, Resource Principal based authentication. 

In this post, we will see how we can enable the resource principal and in particular how we can grant necessary roles to the non admin database user

EXEC DBMS_CLOUD_ADMIN.ENABLE_RESOURCE_PRINCIPAL();

EXEC DBMS_CLOUD_ADMIN.ENABLE_RESOURCE_PRINCIPAL(username => 'USER1');

However if we want non-admin user to enable the resource principal for USER1 then the following needs to be granted to that non-admin user

GRANT EXECUTE ON DBMS_CLOUD_ADMIN TO PROXY_ADMIN_USER;

EXEC DBMS_CLOUD_ADMIN.enable_resource_principal(username => 'PROXY_ADMIN_USER');

GRANT EXECUTE ON ADMIN.OCI$RESOURCE_PRINCIPAL TO PROXY_ADMIN_USER WITH GRANT OPTION;

References:

https://www.oreilly.com/library/view/oracle-database-administration/1565925165/ch06s01s05s01.html


Thursday, 4 November 2021

Gokarna - a budding tourist spot

 It was during the 2021 Diwali holidays and the covid situation was within the control; the initial thought was to go to Goa but it will be overcrowded during the Nov and Dec month and when thought about the alternative we decided to go to Gokarna.

Gokarna beach view from one
of the restaurant in Kudlu beach road

Once Gokarna was mainly the place for workship and performing last rites but in recent few years, it started attracting tourists who like adventures, trekking, water activities, a weekend stay apart from the pilgrimage visit. Gokarna has numerous beaches and each has its own beauty, history, purpose; for example, the main Gokarna beach is used as a pilgrimage site for performing pooja and taking a spiritual bath, the Kudle beach is used for water sport activities, the paradise, and Halfmoon beach hosts tent stay.

Tent stays in Paradise beach


Halfmoon beach where we took bath


All the beaches are well maintained but accessibility wise except Gokarna beach all others require a trek or a boat to reach. The water on the beaches is so clear and transparent, in almost all beaches they have a warning sign of sea vortex. However, than the vortex, the real danger we experienced is by the jellyfishes. It is good to see and observe the jellyfish when we are in the boat but it is really very dangerous when they hit us. Even the slightest touch by the jellyfish will cause skin allergy and will cause pain for a minimum of 30 mins. 

Ferry from Kumta to Gokarna

Jellyfish seen from the ferry




Now coming to the stay, the Kumta is known for lots of private beach resorts and is located 30 km from Gokarna. One such resort is the Silver Sand Beach resort and we stayed there, it is located on the beach so anytime we can go to the beach and take bath, play. If looking to stay closer to Gokarna then there are lots of good stays available on the Kudlu beach road.

The water activities include Banana rides, bumper rides, kayaking, JetSki. There is only one organizer Mystic Gokarna and the prices are a little expensive. Since there is no competitor, bargaining doesn't help. On their website, they mentioned lots of activities but most of them are not available or will be under maintenance. Also, we noticed there was a lack of coordination between the booking counter and the ride conductor. We can take bath on any of the beaches, the beaches like Halfmoon, paradise will be less crowded whereas Om beach and Kudlu beach will be very crowded. The Om beach got its name because of the shape of the beach resembling the Sanskrit Om. 

Water activities in Kudlu beach




Apart from water activities, Gokarna is famous for trekking. It has lots of trekking sites and caves. It has one such cave called Gogarbha and history says that it contains a tunnel to reach Kashi.

Definitely, we should not miss the Maha Ganapati and Mahabaleswar temple; I have never seen a standing Ganapati so far, and here is the first time I saw Ganapati in a standing position in Maha Ganapati temple. Just a few steps away is the famous Mahabaleswar Shiva temple and the temple complex has a shrine for Athmalinga, Devi, and other Gods. There is a strict dress code for men and women to enter the Mahabaleswar temple.

If traveling to Gokarna from Bangalore via road then a short diversion to Jog falls is something not to miss and plan to spend at least 2-3 hours in the Jog to enjoy the complete view and to connect with nature.


The shortcomings of Gokarna are, it is not a mature tourist-friendly place. Getting food of choice is very limited and tastes average, accessibility from one place to another is not so easy. Not all local people are friendly enough for approaching.








Sunday, 15 August 2021

Manacherry dam - One of the dam in Kaveri river

The saying 'We do not know the value when something is close to us' is absolutely true and the lockdown and travel restrictions makes us explore local places and helped us understand the value of nearby places. 

Recently went to these two places without any expectation and to our surprise, we enjoyed ourselves a lot and spent more time than we planned. 

  1. Manacherry dam - https://goo.gl/maps/xrsNdAB2Wuw4QvWt8
  2. Shri Akaasa Vinayakar Temple -  https://goo.gl/maps/ptiYZpNmXZqggTCy8

Sir C.V.Raman told Water is the elixir of life and the rivers are the main reason for civilization, both these places I mentioned above are special for the same reason as it is water abundant place. 

It is in Jul-Aug time of the year and dams are opened irrigation so we can witness the full flow of water in the Kaveri river. When it comes to visiting the Kaveri river dams, we always think of KRS Dam, Kabini Dam, Mettur Dam, Kallanai, of course, all these dams are infrastructural marvels that stand strong for hundreds and hundreds of years and some stands thousands of years like Kallanai. We rarely think of the numerous number of small dams that control the flow of water and hardly visit them. 

One such small dam is the Manacherry dam in Kumbakonam, it is a beautiful place where the Kaveri river divides into Kaveri and Veeracholan rivers. The place is very well maintained and the footsteps in the river bank are clean, we could see a group of children enjoying their day playing in the river water and the other side group of youngsters trying their luck in fishing. As I mentioned the river getting divided, we can go to the land dividing two rivers via the dam structure. 

Some activities we can do are, get down into the river and play with the water, take bath, take nice photos, enjoy nature sights, have some lite snacks or lunch under the tree. There is a temple between the two rivers and we can do meditation as there is no other sound except the sound of water flow!

Its a nostalgic moment for me as I visited this place when I was in school (1999) and visited it again in the year 2021. This visit taught me the below lessons

1. Value of a tree

Its hot summer but when we sit under a tree which is branched out very well near the river bank, we will not feel the hotness of the sun.  

2. Value of a not so famous place

During the covid restriction, it is not encouraged to visit famous attractions. And local places like these are good as it hardly have crowds and we don't have to travel so far.

3. Value of time

It was all like just yesterday I finished school but when I look back, it be already 20 years passed from the time I completed my high-school.

Below are some of the snaps taken in this place

Stream of water from the dam

In the park between the two rivers




Playing in the water stream


Beautiful view of river from the dam

Dam Structure




Temple situated between the two rivers



In the next post I will write about the Shri Akaasa Vinayakar Temple


Tuesday, 6 July 2021

Accessing kube-apiserver from a running pod / Doing a kubectl from a pod

Rarely we want our POD to talk to the kube-apiserver to fetch details about the other deployments, pod status etc. This is not a common usecase but the option provided by K8S can be used in a very creative way to solve problem when a running pod want to know information about the cluster

The logic is very simple, we use the ** kubectl ** command to talk to the kube-apiserver and access the cluster, the kubectl client maintains the details about the cluster in ~/.kube/config directory. And if we want to access the same from the pod then even the pod should contain all the configurations about the cluster so it can access the kube-apiserver

The good news is when kubernetes brings up the pod it mounts all the necessary folder that contains configuration, certificate etc and it will have one default service account attached to the pod. The default service account is authorized to access only a very limited resouce from kube-apiserver

We can create a new service account and authorize it to access additional resources by creating the following items

  1. ServiceAccount
  2. ClusterRole / Role
  3. ClusterRoleBinding / RoleBinding

Choosing between Role and ClusterRole depends on whether we want to access the resource at own namespace only or we need access resources cluster-wide

Usecase: Getting the deployment details from the POD

In this use-case, we are trying to read all the deployments available in the same namespace where the POD is running

Service Account

The first step is to create the service account, it is like a user which we will bind to the role and use it in the deployment/pod

kubectl create sa apps-sa -n vemohanr --dry-run -o yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  creationTimestamp: null
  name: apps-sa
  namespace: vemohanr

Role

We can create one role mentioning about all the resources we need to access or we can create one role per resource.

kubectl create role deployment-reader --verb=list,get --resource=deployment -n vemohanr --dry-run -o yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  creationTimestamp: null
  name: deployment-reader
rules:
- apiGroups:
  - apps
  resources:
  - deployments
  verbs:
  - list
  - get

Role Binding

Resource binding is the place where we will tie the service account with the role

kubectl create rolebinding apps-sa-deployment-reader --serviceaccount=vemohanr:apps-sa --role=deployment-reader -n vemohanr --dry-run -o yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  creationTimestamp: null
  name: apps-sa-deployment-reader
  namespace: vemohanr
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: deployment-reader
subjects:
- kind: ServiceAccount
  name: apps-sa
  namespace: vemohanr

Attach the Service Account to the POD

We need to attach the service account with the deployment so it will get granted access based on the role it is binded with

apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: ubuntu
  name: ubuntu
  namespace: vemohanr
spec:
  replicas: 1
  selector:
    matchLabels:
      app: ubuntu
  template:
    metadata:
      labels:
        app: ubuntu
    spec:
      serviceAccountName: apps-sa
      containers:
      - image: iad.ocir.io/paasdevoic/vemohanr/ubuntu:latest
        name: ubuntu
        command:
        - "sh"
        - "-c"
        - "sleep 10000"
      imagePullSecrets:
      - name: ocirsecret

Quick Testing

For quick testing we can get inside this ubuntu POD and execute the curl command

$ kubectl exec -it ubuntu-5d8cc9cfdf-cxzls -n vemohanr -- sh
$ APISERVER=https://kubernetes.default.svc
$ SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount
$ NAMESPACE=$(cat ${SERVICEACCOUNT}/namespace)
$ TOKEN=$(cat ${SERVICEACCOUNT}/token)
$ CACERT=${SERVICEACCOUNT}/ca.crt
$ CACERT=${SERVICEACCOUNT}/ca.crt
$ curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" -X GET ${APISERVER}/api/apis/apps/v1/deployments

Client Libraries

There are client libraries available in most of the language and we can get info about it from https://kubernetes.io/docs/reference/using-api/client-libraries/

Reference

https://kubernetes.io/docs/tasks/run-application/access-api-from-pod/ https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/

Saturday, 29 May 2021

How to grow Rose plant from cut stem

 In this post, I want to share how we can nurture the rose stem and grow it into a plant. The most important one that we need is patience because it will take 2-3 weeks at least to see the result. The real fun is on seeing how the soil and the necessary environment is giving nutrients to the cut stem and makes into a plant and we could see it growing day-by-day. 

The technique that I experimented is the greenhouse gardening technique where we will cover the whole pot inside a plastic cover so it can allow the visible light into the pot but will not allow the heat outside and keep the environment warmer.

Interesting read about the Greenhouse 

https://www.proflowers.com/blog/greenhouse-gardening-guide/
http://hyperphysics.phy-astr.gsu.edu/hbase/thermo/grnhse.html

Also since the stem do not contain the roots, we can help the stem to get root faster by using some rooting hormones. Few of the natural rooting hormones are natural honey, alovera plant gel, tulsi water etc, basically any natural product which has anti-bacterial and anti-fungal properties can be used. We can also use artificial rooting hormones as well but natural one does pretty well. The function of the rooting hormone is to protect the stem from bacteria, diseases etc. 

Interesting read about rooting harmones

https://www.urbangardengal.com/honey-rooting-hormone-cuttings/

Next is the selection of stem, we should select a healthy stem so the success rate will be high. The healthy rose stem are the one that are dark green in color without any black spots, no fungus etc. 

Lets see the process in sequence of steps

Step 1: Identify the healthy stem from the parent plant 

Step 2: Keep all the necessary tools and materials ready like the pot, scissor, knife, rooting harmone, cover etc

Step 3: Cut the stem into multiple small pieces, desirable not more than an 5-6 inches. And cut it at a 45 degree angle

Step 4: Clean the side of stem which we will insert in the soil

Step 5: Dip the side with the rooting harmone

Step 6: Keep the pot ready with right mix of soil and water. Most important info is we should not water the plant after inserting the stem, so add necessary water before inserting the stem. The reason is that if we pour water then the root harmone will disolve and get mixed into the soil.

Step 7: Insert the cut stem into the pot with some distance between them

Step 8: Cover the pot with a plastic cover and keep it in a low sunlight shade. When it is in greenhouse effect we don't have to water them everyday. The moisture will circulate within the closed area and will keep the soil wet.

Step 9: After a week we can open and check its health and cover it again

Step 10: After 2 weeks, once we see the leaves, we can make a small hole in the cover to allow leaves to get some fresh air to breath

Step 11: After 3 weeks, we can remove the greenhouse effect and either repot it or grow in the same pot

Happy Gardening!!