Using kubectl to jumpstart a YAML file — #HeptioProTip

Joe Beda
Heptio
Published in
2 min readSep 21, 2017

--

When getting started with Kubernetes, it is super easy to use kubectl run to imperatively get stuff going. But advanced features and a careful workflow demand that you use a YAML file.

Often times I found myself pulling up the Kubernetes documentation to for an example similar to what I wanted and then copy/pasting that into my editor. This always took much longer than it should have. Here is a quick tip to jumpstart things.

If you already have something running, you can extract the YAML in a way that is ready to check in by running something like:

kubectl get deployment my-cool-app -o yaml --export \
> my-cool-app.yaml

This dumps the YAML from the server but also asks it to strip out all the stuff that isn’t specified by the user. This may or may not do 100% of what you want but it’ll get you pretty close.

If, instead, you want to create a YAML file from scratch, you can just run

kubectl run my-cool-app —-image=me/my-cool-app:v1 \
-o yaml --dry-run > my-cool-app.yaml

The YAML file will have something like this:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
creationTimestamp: null
labels:
run: my-cool-app
name: my-cool-app
spec:
replicas: 1
selector:
matchLabels:
run: my-cool-app
strategy: {}
template:
metadata:
creationTimestamp: null
labels:
run: my-cool-app
spec:
containers:
- image: me/my-cool-app:v1
name: my-cool-app
resources: {}
status: {}

You can use the -o yaml --dry-run flags with kubectl run or kubectl create <OBJECT>. For example, try kubectl create secret generic my-secret --from-literal=foo=bar -o yaml --dry-run > my-secret.yaml.

Hope you enjoyed this #HeptioProTip! Follow @heptio for more tips and tricks.

--

--

Dad of two. CTO of Heptio. Started Google Compute Engine, Kubernetes and Google Container Engine.