Fatskills
Practice. Master. Repeat.
Study Guide: Kubernetes - CKA
Source: https://www.fatskills.com/kubernetes/chapter/kubernetes-cka

Kubernetes - CKA

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~20 min read

Create a namespace called ggckad-s0 in your cluster.
Run the following pods in this namespace.
A pod called pod-a with a single container running the kubegoldenguide/simple-http-server image
A pod called pod-b that has one container running the kubegoldenguide/alpine-spin:1.0.0 image, and one container running nginx:1.7.9
Write down the output of kubectl get pods for the ggckad-s0 namespace.
kubectl create namespace ggckad-s0
kubectl run pod-a --image kubegoldenguide/simple-http-server -n ggckad-s0
kubectl run pod-b--image kubegoldenguide/apline-spin:1.0.0
kubectl run pod-b--image nginx:1.7.9

What is a pod?
group of one or more containers, with shared storage/network, and a specification for how to run the containers.

What is a service?
A Service is an abstraction which defines a logical set of Pods and a policy by which to access them.

What is kubelet?
An agent service which runs on each node and enables the slave to communicate with the master.

What is kubectl-proxy?
A network proxy which reflects the services as configured in Kubernetes API on each node.

What does the kube-apiserver do?
The API server is a component of the Kubernetes control plane that exposes the Kubernetes API. The API server is the front end for the Kubernetes control plane.

What does the kube scheduler do?
The kube-scheduler is responsible for scheduling and distribution, and management of workloads on the worker nodes.

What is ETCD and what does it do for Kubernetes?
Consistent and highly-available key value store used as Kubernetes' backing store for all cluster data.

What is Ingress?
Ingress exposes HTTP and HTTPS routes from outside the cluster to services within the cluster. Traffic routing is controlled by rules defined on the Ingress resource.

What is an ingress controller? Give some examples of Ingress Controllers.
An Ingress controller is responsible for fulfilling the Ingress, usually with a load balancer, though it may also configure your edge router or additional frontends to help handle the traffic. Ambassador, ISTIO, NGINX.

What are the types of ingress?
Single Service, SImple Fanout, Name Based Virtual Hosting, TLS, Load Balancing.

All operations in this question should be performed in the ggckad-s2 namespace.
Create a ConfigMap called app-config that contains the following two entries:

'connection_string' set to 'localhost:4096'
'external_url' set to 'google.com'
Run a pod called question-two-pod with a single container running the kubegoldenguide/alpine-spin:1.0.0 image, and expose these configuration settings as environment variables inside the container.
kubectl create configmap my-config --from-literal=connection_string=localhost:4096 --from-literal=external_url=google.com -n ggckad-s2

apiVersion: v1
kind: Pod
metadata
: name: question-two-pod
namespace: ggckad-s2
spec:
containers
- image: kubegoldenguide/alpine-spin:1.0.0
name: container-a envFrom:
- configMapRef:
name: app-config

Security: Name some ways you can secure a Kubernetes cluster
Control access to the Kubernetes API
Control access to kublet
Control the capabilities of a workload or user at runtime
protect cluster components from compromise

Security: Names some ways you can control access to the Kubernetes API?
Transport layer security for all API traffic
API authentication/authorization,

Security: What can you do to control access to the kublet
Kubelets expose HTTPS endpoints which grant control over the node and containers. By default Kubelets allow unauthenticated access to this API.

Production clusters should enable Kubelet authentication and authorization.

Security: Name some ways you can control the capabilities of a workload or user at runtime.
Limit resource usage on a cluster
Controlling what privileges containers run with
Restrict network access
Restrict cloud metadata API access
Control with nodes pods may access.

Security: How to you protect cluster component from compromise
Restrict access to etcd
Enable audit logging
Restrict access to alpha and beta features
Rotate infrastructure credentials frequently
Review third party integrations before enabling them
Encrypt secrets at rest.
Tune into the kubernetes-annouce group for emails about security announcements.

Dump pod logs for a pod called "my-pod" (stdout)
kubectl logs my-pod

dump pod logs for all pods with label env=production (stdout)
kubectl logs -l env=production

dump pod logs (stdout) for a previous instantiation of a pod called "my-pod"
kubectl logs my-pod --previous

dump pod container logs for a container called "my-container" running in a pod called "my-pod" to stdout.
kubectl logs my-pod -c my-container

dump pod logs, with label name=myLabel (stdout) for a container called my container
kubectl logs -l name=myLabel -c my-container

stream pod logs (stdout) for a pod called 'my-pod'
kubectl logs -f my-pod

Run a 'busybox' pod as interactive shell
kubectl run -i --tty busybox --image=busybox -- sh

Show metrics for a given pod called "my-pod" and its containers
kubectl top pod my-pod --containers

Run a directory listing command in existing pod called 'my-pod' (multi-container case) in container called 'my-container'
kubectl exec my-pod -c my-container -- ls /

Mark node called "my-node" as unschedulable
kubectl cordon my-node

Drain node "my-node" in preparation for maintenance
kubectl drain my-node

Mark "my-node" as schedulable
kubectl uncordon my-node

Show metrics for a given node
kubectl top node my-node

Dump current cluster state to stdout
kubectl cluster-info dump

Create a busybox pod (using kubectl command) that runs the command "env". Run it and see the output
kubectl run busybox --image=busybox --command --restart=Never -- env
# and then, check its logs
kubectl logs busybox

Create a busybox pod (using YAML) that runs the command "env". Run it and see the output
kubectl run busybox --image=busybox --restart=Never --dry-run -o yaml --command -- env > envpod.yaml

cat envpod.yaml
kubectl apply -f envpod.yaml
kubectl logs busybox

Get the YAML for a new ResourceQuota called 'myrq' with hard limits of 1 CPU, 1G memory and 2 pods without creating it
kubectl create quota myrq --hard=cpu=1,memory=1G,pods=2 --dry-run -o yaml

Create a pod with image nginx called nginx and allow traffic on port 80
kubectl run nginx --image=nginx --restart=Never --port=80

Dexterity: Run a single instance of nginx in a pod. Change pod's image to nginx:1.7.1. Observe that the pod will be killed and recreated as soon as the image gets pulled
kubectl set image pod/nginx nginx=nginx:1.7.1
kubectl describe po nginx
# you will see an event 'Container will be killed and recreated'

kubectl get po nginx -w

Dexterity: List all supported resource types along with their shortnames
kubectl api-resources

Dexterity: If a pod called 'nginx' crashed and restarted, how would you get logs about the previous instance
kubectl logs nginx -p

Dexterity: Create a pod called 'busybox' using the 'busybox' image that echoes 'hello world' and then exits
kubectl run busybox -it --image=busybox --restart=Never -- echo 'Hello World!'

Dexterity: Open a shell on a running pod called'nginx'
kubectl exec -it nginx -- /bin/sh

Dexterity:
* Create a secret that has the following username password data:
> username=missawesome
> password=123kube321
* Create a pod running nginx that has access to those data items in a volume mount path at ```/tmp/secret-volume```
* log into the nginx pod you created and list the items and cat the output of the data items to a file "credentials.txt"
echo -n 123kube321 | base64

kubectl create secret generic test-secret --from-literal=username=missawesome --from-literal=password=MTIza3ViZTMyMQ== -o yaml --dry-run > test-secret.yaml

apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: secret-pod
name: secret-pod
spec:
containers:
- image: nginx
name: secret-pod
volumeMounts:
- name: secret-volume
mountPath: /tmp/secret-volume
resources: {}
volumes:
- name: secret-volume
secret: secretName: test-secret

### go into the pod, then list the contents of /tmp/secret-volume
kubectl exec -it secret-pod /bin/bash

Dexterity: Generate yaml for a pod called mypod running the nginx image using Kubectl
kubectl run mypod --image nginx --restart Never --dry-run -o yaml > pod.yaml

Dexterity: Generate yaml for a deployment called my-deployment running the nginx:1.7.9 image using Kubectl
[v1.17] kubectl run my-deployment --image nginx:1.7.9 --restart Always --dry-run -o yaml > deployment.yaml

[v1.18] kubectl create deployment my-deployment --image nginx:1.7.9 -o yaml --dry-run=client

Dexterity: Generate yaml for a job called myjob running the nginx image using Kubectl
kubectl run myjob --image nginx --restart OnFailure --dry-run -o yaml > job.yaml

Dexterity: Generate the yaml to create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000
kubectl expose rc nginx --port=80 --target-port=8000

Dexterity: Create a service for a replication controller identified by type and name specified in "nginx-controller.yaml", which serves on port 80 and connects to the containers on port 8000
kubectl expose -f nginx-controller.yaml --port=80 --target-port=8000

Dexterity: Create a service for a pod valid-pod, which serves on port 444 with the name "frontend"
kubectl expose pod valid-pod --port=444 --name=frontend

Dexterity: Create a second service based on the existing service called nginx exposing the container port 8443 as port 443 with the name "nginx-https"
kubectl expose service nginx --port 443 --target-port 8443 --name nginx-https

Dexterity: Create a service for a replicated streaming application on port 4100 balancing UDP traffic and named 'video-stream'
kubectl expose rc streamer --port=4100 --protocol=UDP --name=video-stream

Dexterity: Create a headless service for an nginx deployment, which serves on port 80 and connects to the containers on port 8000
kubectl expose deployment nginx --port=80 --target-port=8000 --cluster-ip None

Dexterity: list all pods in every namespace and sort them by name
kubectl get pods --sort-by={.metadata.name} --all-namespaces

Dexterity: Retrieve the logs of pod associated with deployment 'mydeployment'
kubectl get pods --selector=run=mydeployment
kubectl logs mydeploment-pod

Dexterity: Start a single instance of hazelcast and set labels "app=hazelcast" and "env=prod" in the
container. Expose port 5701.
kubectl run hazelcast --image=hazelcast --labels="app=hazelcast,env=prod" --port 5701

Start a replicated instance of nginx. (5 times replicated)
kubectl run nginx --image=nginx --replicas=5

Start a pod of busybox and keep it in the foreground, don't restart it if it exits.
kubectl run -i -t busybox --image=busybox --restart=Never

Start the perl container to compute π to 2000 places and print it out.
kubectl run pi --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'

Start the cron job to compute π to 2000 places and print it out every 5 minutes.
kubectl run pi --schedule="0/5 * ?" --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle'print bpi(2000)'

how do you query the api server for a list of all API Groups?
kubectl api-resources

Query the api server for all objects available on the "apps" API Group
kubectl api-resources --api-groups=apps

Query the api server for details on the latest version of the 'deployment' resource.
kubectl explain deployment | head

Query the api server for the details on the 'deployment' resource at version 'apps/v1beta2'
kubectl explain deployment --api-version apps/v1beta2 | head

Print a sorted list of the supported API versions
kubectl api-versions | sort

use 'kubectl' to configure a watch on pods in the default namespace
kubectl get pods --watch

Which two settings for restartPolicies must a Daemonset have?
A Pod Template in a DaemonSet must have a RestartPolicy equal to Always, or be unspecified, which defaults to Always.

Resource Limits: Name the two resource types known as compute resources and the unit that they are specified in
CPU is specified in units of cores
Memory is specified in units of bytes

Scheduling: Manually schedule a pod called 'my-pod' with image 'nginx' on 'node01'
kubectl run my-pod --image nginx --dry-run -o yaml --restart Never > pod.yaml

Then add 'nodeName: node01' to the spec

Scheduling: Write the YAML to Label node 'node01' with the label nvme-ssd: true.

Then generate the yaml to deploy a pod called 'my-pod' running nginx on that node:
kubectl label nodes node01 ssd=true

kubectl run my-pod --image nginx --dry-run -o yaml --restart Never > pod.yaml

Then add the following to the spec:

nodeSelector:
nvme-ssd: true

Scheduling: Name and describe two different steps that kube-scheduler uses to schedule a pod on a node
- Filtering - finds the set of Nodes where it's feasible to schedule the Pod
- Scoring - the scheduler ranks the remaining nodes to choose the most suitable Pod placement.

Scheduling: name two supported ways of configuring the scheduler filtering and scoring behavior
Scheduling Policies allow you to configure Predicates for filtering and Priorities for scoring.

Scheduling Profiles allow you to configure Plugins that implement different scheduling stages, including: QueueSort, Filter, Score, Bind, Reserve, Permit, and others. You can also configure the kube-scheduler to run different profiles.

Scheduling: How do you display scheduler events?
'kubectl describe pod' and look at its scheduler events or
kubectl get events --field-selector reason=scheduled
kubectl get events --field-selector reason=FailedScheduling

Scheduling: How do you set a scheduling policy
You can set a scheduling policy by running
kube-scheduler --policy-config-file <filename>
or
kube-scheduler --policy-configmap <ConfigMap> and using the Policy type.

Scheduling: how do you set a schedule profile
kube-scheduler --config <filename>

Monitoring: Name three ways you can Manage cluster component logs.
While Kubernetes does not provide a native solution for cluster-level logging, there are several common approaches you can consider. Here are some options:
- Use a node-level logging agent that runs on every node.
- Include a dedicated sidecar container for logging in an application pod.
- Push logs directly to a backend from within an application.

Deployments: Perform a rolling update by creating a deployment called "nginx-deployment" of nginx:1.14.2 with 3 replicas that exposes port 80. Then upgrade that deployment to use nginx:1.16.1
kubectl run nginx-deployment --image nginx:1.14.2 --port 80 --replicas 3 --restart Always

kubectl set image deployment/nginx-deployment nginx=nginx:1.16.1 --record

Deployments: Perform a rolling update by creating a deployment called "nginx-deployment" of nginx:1.14.2 with 3 replicas that exposes port 80.

Update the image to nginx:1.161 (which breaks it),

Verify the rollout status

Check the rollout history of the deployment

Then perform a rollback.to the previous version of the deployment
kubectl run nginx-deployment --image nginx:1.14.2 --restart Always --port 80

kubectl set image deployment.v1.apps/nginx-deployment nginx-deployment=nginx:1.161 --record true

kubectl rollout status deployment.v1.apps/nginx-deployment

kubectl rollout history deployment.v1.apps/nginx-deployment

kubectl rollout undo deployment.v1.apps/nginx-deployment --to-revision=1

Deployments: Scale a deployment by creating a deployment called "nginx-deployment" of nginx:1.14.2 with 3 replicas that exposes port 80.

scale it up to 5 pods
kubectl run nginx-deployment --image nginx:1.14.2 --port 80 --replicas 3 --restart Always
kubectl scale nginx-deployment --replicas 5

Cluster Maintenance: What are the three steps of the cluster upgrade workflow.
1. Upgrade the primary control plane node.
2. Upgrade additional control plane nodes.
3. Upgrade worker nodes.

How do you install Docker on Ubuntu?
sudo apt-get update && sudo apt-get install docker.io -y

sudo groupadd docker

sudo usermod -aG docker $user

How do you install kubeadm on Ubuntu?
cat <<EOF > k8s.conf
net.bridge.bridge-nf-ip6tables = 1
net bridge.bridge-nf-iptables = 1
EOF

sudo mv k8s.conf /etc/sysctl.d/k8s.conf

sydo sysctl --system

sudo apt-get update && sudo apt-get install -y apt-transport-https curl

curl -s https://packages.cloud.google.com/apt/docl/apt-key.gpg | sudo apt-key add -

sudo apt-get update

sudo apt-get install -y kubelet kubeadm kubectl

sudo apt-mark hold kubelet kubeadm kubectl

TMUX: Start a new tmux session with three panes for controller-0, worker-0, worker-1
tmux new-session

[ctrl-b] + = (do 2 times)

Monitoring: How to you get the kubelet logs and follow them?
If you run kubelet using systemd: journalctl -u kubelet -f

Smoketest: Verify that secrets are encrypted at rest. Create a generic secret called "kubernetes-the-hard-way" with a name-value pair of "mykey=mydata". Then print a hexdump of this secret stored in etcd to verify that it is encrypted at rest.
kubectl create secret generic kubernetes-the-hard-way --from-literal="mykey=mydata"

gcloud compute ssh controller-0 --command "sudo ETDCTL_API=3 etcdctl get --endpoints+https://127.0.0.1:2379 --cacert=/etc/etcd/ca.pem --cert=/etc/etcd/kubernetes-pem --key=/etc/etcd/kubernetes-key.pem /registry/secrets/default/kubernetes-the-hard-way | hexdump -C"

Smoketest: Verify the cluster can create and manage deployments by creating a deployment for the nginx web server, then list the pod created by the deployment.
kubectl create deployment nginx --image=nginx

kubectl get pods -l app=nginx

Smoketest: Verify the ability to access application remotely using port forwarding create a deployment for the nginx web server, then forward port 8080 on your local machine to port 80 of the nginx pod
kubectl create deployment nginx --image=nginx

POD_NAME=$(kubectl get pods -l app=nginx -o jsonpath="{.items[0].metadata.name}")

kubectl port-forward $POD_NAME 8080:80

curl --head http://127.0.0.1:8080

Smoketest: Verify the ability to execute commands in a running container. Create a deployment for the nginx web server, then execute 'nginx -v' inside of it.
kubectl create deployment nginx --image=nginx

POD_NAME=$(kubectl get pods -l app=nginx -o jsonpath="{.items[0].metadata.name}")

kubectl exec -ti $POD_NAME -- nginx -v

Smoketest: Create a deployment for the Nginx web server and expose the deployment on port 80 using NodePort. Then retrieve the port assigned to the service.
kubectl create deployment nginx --image nginx

NODE_PORT=$(kubectl get svc nginx --output=jsonpath='{range .spec.ports[0]}{.nodePort}')

Cluster Maintenance: Take a snapshot of the etcd database on the cluster controller. Then Verify the snapshot file size.
gcloud compute ssh controller-0

ETCDCTL_API=3; sudo etcdctl --endpoints 127.0.0.1:2397 snapshot save snapshot.db

ETCDCTL_API=3; sudo etcdctl --write-out=table snapshot status snapshot.db

ETCDCTL_API=3; etcdctl --write-out=table snapshot status snapshotdb

Cluster Maintenance: What are the steps involved with replacing a failed etdc member?
#Get the member id of the failed member
ETCDCTL_API=3; etcdctl --endpoints https://10.240.0.10:2379,https://10.240.0.11:2379,https://10.
240.0.12:2379 --cacert /var/lib/kubernetes/ca.pem --cert /var/lib/kubernetes/kubernetes.pem --key /var/lib/kubernetes/kubernetes-key.pem member list

#Remove the failing member by it's id:
etcdctl member remove 8211f1d0f64f3269

#Add the new member #3
etcdctl member add controller-3 --peer-urls=https://10.240.0.13:2379

# Start the new member
export ETCD_NAME="controller-3"
export ETCD_INITIAL_CLUSTER="controller-0=https://10.240.0.10:2379,controller-1=https://10.240.0.11:2379,controller-2=https://10.240.0.12:2379"
export ETCD_INITIAL_CLUSTER_STATE=existing
etcd [flags]

Security: How do you enable RBAC on a cluster and how can you check if it is enabled?
To enable RBAC, start the API server with the --authorization-mode flag set to a comma-separated list that includes RBAC.

To verify cat '/etc/systemd/system/kube-apiserver.service'

Security: RBAC - Create a cluster role that allows for read access to secrets in any particular namespace or cluster-wide
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
# "namespace" is omitted for ClusterRoles
name: secret-reader
rules:
- apiGroups: [""]
#at the HTTP level, the name of the resource for accessing Secret
# objects is "secrets"
resources: ["secrets"]
verbs: ["get", "watch", "list"]

Security: RBAC - Create a rolebinding that binds a cluster role called "secret-reader" to the user called "bob"
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding metadata: name: secrets-reader namespace: default subjects: - kind: User name: bob apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: secrets-reader apiGroup: rbac.authorization.k8s.io

Security: RBAC - Create a CustlerRole Binding that allows anyone in in the "manager" group to read secrets in any namespace.
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: read-secrets-manager subjects: - kind: Group name: manager apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: secret-reader apiGroup: rbac.authorization.k8s.io

Security: Quickly show which admission control plugins are enabled via the command line
kube-apiserver -h | grep enable-admission-plugins

Security: Quickly show which authentication mechanisms that can be enabled via the command line. Next show all authentication mechanisms that are enabled in the cluster
kube-apiserver -h | grep authorization-mode
cat /etc/systemd/system/kube-apiserver.service | grep authorization

Security: Define the yaml for a pod called "security-context-example" that will run as the user 1000 in group 3000 with file system group 2000.
Use the 'busybox' image and run the command "sh -c sleep 1h" on startup. Also , mount an empty directory volume named "sec-stx-demo" at path /data/demo in the pod.

disallow privilege escalation
# Get a head start by generating the yaml
kubectl run security-context-example --image busybox --dry-run -o yaml --command 'sh' -- '-c' 'sleep 1h'

# manually edit the resulting yaml adding the volume and security contexts

apiVersion: v1
kind: Pod
metadata
: name: security-context-demo
spec: securityContext
runAsUser: 1000
runAsGroup: 3000
fsGroup: 2000
volumes
: - name: sec-ctx-vol
emptyDir: {}
containers:
- name: sec-ctx-demo
image: busybox
command: [ "sh", "-c", "sleep 1h" ]
volumeMounts:
- name: sec-ctx-vol
mountPath: /data/demo
securityContext:
allowPrivilegeEscalation: false

Security: Create a file called username.txt and password txt with the values 'foo' and 'bar' respectively, Generate a secret name "generic-credentials' from these files with username and password fields.
echo -n foo > username.txt
echo -n bar > password.txt
kubectl create secret generic-credentials --from-file username.txt --from-file password.txt

Security: Create a generic secret called 'dev-db-secret' from string literals with fields username=devuser and password='S!B\*d$zDsb='
kubectl create secret generic dev-db-secret --from-literal=username=devuser --from-literal=password='S!B\*d$zDsb='

Dexterity: Assign a label to a control plane node marking it as having a disktype 'ssd'. Run an NGINX pod exposing container port 80 and set it up so that it runs on the node with label disktype 'ssd'
#kubectl label nodes <node-name> <label-key>=<label-value>
kubectl label node kubemaster disktype=ssd

kubectl run nginx --restart Never --image nginx --port 80 --dry-run -o yaml > example.yaml

#Then edit example.yaml to include
nodeSelector:
disktype: ssd

#lastly
kubectl apply -f example.yaml

Monitoring: where are each of the logs for the control plane node? (*note you need to know which three component processes you are looking for here)
kube-apiserver: /var/logs/kube-apiserver.log
scheduler: /var/log/kube-scheduler.log
kube-controller-manager: /var/log/kube-controller-manager.log

Monitoring: where are each of the logs for a typical worker node kept?
kubelet: /var/log/kubelet.log
kube-proxy: /var/log/kube-proxy.log

Name some ways you can mitigate involuntary disruptions of pods
Ensure your pod requests the resources it needs.
Replicate your application across nodes.
Spread your app across zones or racks.

Security: Define an simple pod security policy in a yaml file that prevents the creation of privileged pods.
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: example
spec:
privileged: false # Don't allow privileged pods!
# The rest fills in some required fields.
seLinux:
rule: RunAsAny
supplementalGroups:
rule: RunAsAny
runAsUser:
rule: RunAsAny
fsGroup:
rule: RunAsAny
volumes: - '*'

Dexterity: Retrieve the node-port assigned to a service called NGINX into a variable ('Bash command')
NODE_PORT=$(kubectl get svc nginx \ --output=jsonpath='{range .spec.ports[0]}{.nodePort}')

Dexterity: Retrieve the pod name for a deployment that was created using the 'kubectl run' command running busybox
POD_NAME=$(kubectl get pods -l run=busybox -o jsonpath="{.items[0].metadata.name}")

Dexterity: Determine the domain name by running busybox and performing an nslookup.
kubectl run busybox --image busybox:1.28 --command -- sleep 3600

POD_NAME=$(kubectl get pods -l run=busybox -o jsonpath="{.items[0].metadata.name}")

kubectl exec -it ${POD_NAME} -- nslookup kubernetes

Dexterity: Fetch the image used in a pod called 'nginx' into a BASH variable without using the 'describe' pragma.
kubectl get po nginx-alt -o jsonpath='{.spec.containers[].image}{"\n"}'

Dexterity: List all the pods in cluster and sort them by name
kubectl get pods --all-namespaces --sort-by=.metadata.name

Security: How do you enable PodSecurityPolicy on a cluster
add "PodSecurityPolicy" to the --enable-admissions-plugins property on the file /etc/systemd/system/kube-apiserver.yaml (For systemd systems )

Otherwise add it in /etc/kubernetes/manifests/kube-apiserver.yaml

Roles: Create a role named "pod-reader" that allows the user to perform "get", "watch" and "list" on pods
kubectl create role pod-reader --verb=get --verb=watch --verb=list --resource=pods

Roles: Create a Role named "pod-reader" with ResourceName specified
kubectl create role pod-reader --verb=get --resource=pods --resource-name=readablepod

Role: Create a role named "foo" with API Group Specified
kubectl create role foo --verb=get,list,watch --resource=rs.extensions

Dexterity: Get the YAML for a new ResourceQuota called 'myrq' with hard limits of 1 CPU, 1G memory and 2 pods without creating it
kubectl create quota myrq --hard=cpu=1,memory=1G,pods=2 --dry-run -o yaml

Dexterity: Create a Pod with two containers, both with image busybox and command "echo hello; sleep 3600". Connect to the second container and run 'ls'
kubectl run multi --image busybox --dry-run -o yaml --restart Never -- /bin/sh -c "echo hello; sleep 3600"

#edit the yaml make sure to rename the containers

kubectl exec -it multi -c two /bin/sh

Dexterity: Create 5 nginx pods in which two of them is labeled env=prod and three of them is labeled env=dev
kubectl run nginx-dev1 --image=nginx --restart=Never --labels=env=dev
kubectl run nginx-dev2 --image=nginx --restart=Never --labels=env=dev
kubectl run nginx-dev3 --image=nginx --restart=Never --labels=env=dev
kubectl run nginx-prod1 --image=nginx --restart=Never --labels=env=prod
kubectl run nginx-prod2 --image=nginx --restart=Never --labels=env=prod

Dexterity: List all the pods showing name and namespace with a json path expression
kubectl get pods -o=jsonpath="{.items[*]['metadata.name', 'metadata.namespace']}"

Create a pod disruption budget named my-pdb that will select all pods with the app=rails label and require at least one of them being available at any point in time.
kubectl create poddisruptionbudget my-pdb --selector=app=rails --min-available=1

Create a pod disruption budget named my-pdb that will select all pods with the app=nginx label and require at least half of the pods selected to be available at any point in time.
kubectl create pdb my-pdb --selector=app=nginx --min-available=50%



ADVERTISEMENT