How to create and edit Kubernetes yaml files on the fly

Deployments in a GIF

As I study for the Certified Kubernetes Administrator (CKA) Exam, I’ve found that creating pods and deployments using kubectl run and kubectl create with the --dry-run=client flag has been very helpful and saves a ton of time.

Create a basic NGINX Pod

$ kubectl run nginx --image=nginx

This will create an nginx pod on the cluster.

$ kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 7s

Create a pod yaml file without actually creating the pod

$ kubectl run nginx --image=nginx --dry-run=client -o yaml

This will output a yaml file you can then apply/create or update as needed.

apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
containers:
- image: nginx
name: nginx
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Always
status: {}

Create a deployment

$ kubectl create deployment --image=nginx nginx

This creates a deployment without needing to go fetch a deployment yaml.

$ kubectl get deployments
NAME READY UP-TO-DATE AVAILABLE AGE
nginx 1/1 1 1 7s

Create a deployment yaml without actually creating the deployment

$ kubectl create deployment --image=nginx nginx --dry-run=client -o yaml

This will give you a template for creating a deployment.

apiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
labels:
app: nginx
name: nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx
strategy: {}
template:
metadata:
creationTimestamp: null
labels:
app: nginx
spec:
containers:
- image: nginx
name: nginx
resources: {}
status: {}

Create a deployment yaml and redirect it to a file

You can do the same thing as the above, while just redirecting it to a file.

$ kubectl create deployment --image=nginx nginx --dry-run=client -o yaml > nginx-deployment.yaml

If you want to then change the number of replicas, for example, you can simply edit the file using vim.

Another helpful kubectl tool is edit, which you can use to make quick updates to your yaml. For example, after applying the previously created file:

$ kubectl apply -f nginx-deployment.yaml
deployment.apps/nginx created

You can directly edit the deployment yaml as follows:

$ kubectl edit deployment/nginx

Any changes you make using kubectl edit won’t be applied directly to the underlying yaml file. In this case, the nginx-deployment.yaml.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Joe Cardillo

Joe Cardillo

Technical Support Engineer at Linode | Linux & Kubernetes