When you get started with Kubernetes, the first thing you will probably do is create a Deployment using the
kubectl command-line interface. When you create an object in Kubernetes, including a Deployment, you must provide the object spec that describes its desired state, as well as some basic information about the object (such as a name). Most often, you provide this information using a YAML file. This post will explore how to use
kubectl, and commands that you may already be familiar with, to generate this YAML.
First, by way of example, to create a Pod using
kubectl you could run the following command:
Alternatively, you could write the following YAML in pod.yaml:
And, then run:
Both of these approaches are valid and generate exactly the same result in Kubernetes. While
kubectl has a certain simplicity about it, using YAML has two key advantages over running commands manually:
- You can add YAML files to source control to track changes.
- You can create more complex structures with YAML than you can with the command line.
Can you get the best of both worlds? Yes. You can use
--dry-run -o yaml to instruct
kubectl to output the equivalent YAML without actually sending the object to Kubernetes.
--dry-run- If true, only print the object that would be sent, without sending it.
-o yaml- Sets the output format to YAML.
These two options can be added to many commands in
kubectl run and
Generate YAML for a Kubernetes Pod
Generate YAML for a Kubernetes Deployment
Generate YAML for a Kubernetes Service
Write YAML to a file
--dry-run -o yaml you can instruct
kubectl to output YAML. You can then use
> to redirect the output of the command to a file, in this case, called deployment.yaml.
Append an object to an existing file
A Kubernetes YAML file can include the definition of multiple objects - each separated by
---. You can use
>> to redirect the output of a command to a file, appending the output to the existing contents of the file. For example, you could append a Service to expose
my-deploy in deployment.yaml
Note: You will need to run
kubectl apply -f deployment.yaml first, else Kubernetes won’t be able to find
Writing Kubernetes objects in YAML can often be a daunting task. Hopefully, with these simple tips and tricks, you will be able to bootstrap more consistent YAML files with ease. The key thing to take away is
--dry-run -o yaml.
Do you have any
kubectl tips and tricks? If you do, please share them in the comments below!