« Back to home

Generating Kubernetes configuration files using Kubectl

When you're new to Kubernetes creating the Kubernetes configuration files starting with a blank editor window can be quite daunting. One option is to copy an existing file from somewhere and editing it but this can be problematic as there may be alot of noise or perhaps old API versions neither of which are helpful when you're just starting out.

A handy tip is to use the Kubectl (the Kubernetes CLI) to generate a minimal configuration file for you. This will ensure the file is matched to the version of Kubernetes you're using and shouldn't contain too much extraneous information.

Using the -o flag Kubectl can output the result of most commands in a format you specify which you can then pipe to a file. You can additionally add the the --dry-run flag in your command which ensures the command isn't executed but you still get the output, this allows you to start with a basic file and then add additional settings as you need.

If I wanted to create a basic deployment yaml file I can run the following

kubectl run hello-world --image=shahiddev/k8s:1.0 --port=80 --dry-run -o yaml > mydeployment.yaml

This will output a yaml file similar to this


Similarily if I want to create a load balancer service for my deployment I can do the following (note: you'll need to have created the deployment above before running this)

kubectl expose deployment hello-world --port=80 --type=LoadBalancer --dry-run -o yaml > myservice.yaml

This will output a more comprehensive yaml file similar to this


You can omit the --dry-run flag if you want the resource to be created at the same time that the file is created.

Another useful option is to extract the yaml file from an existing deployment

kubectl get deployment hello-world -o yaml > myexistingdeployment

This will output a yaml file similar to this


Hope this tip helps some people overcome the inertia of getting starting with the Kubernetes configuration files.