Create a yaml template using kubectl

2 min read | by Jordi Prats

When you create a new deployment you usually focus on:

  • Number of replicas
  • How you are going to select the pods that are going to be managed by this deployment
  • Pod template

Beside this, all the other required lines on the yaml are boilerplate so it's quite easy to forget about them.

Using kubectl create in dry-run mode and setting the output as yaml we can get the yaml file it would use to create a new resource without actually applying any change:

$ kubectl create deployment demo --dry-run=client --image=nginx -r 3 -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: demo
  name: demo
spec:
  replicas: 3
  selector:
    matchLabels:
      app: demo
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: demo
    spec:
      containers:
      - image: nginx
        name: nginx
        resources: {}
status: {}

We can create most resources this way, but not every single available resource:

$ kubectl create --help
(...)
Available Commands:
  clusterrole         Create a ClusterRole.
  clusterrolebinding  Create a ClusterRoleBinding for a particular ClusterRole
  configmap           Create a configmap from a local file, directory or literal value
  cronjob             Create a cronjob with the specified name.
  deployment          Create a deployment with the specified name.
  ingress             Create an ingress with the specified name.
  job                 Create a job with the specified name.
  namespace           Create a namespace with the specified name
  poddisruptionbudget Create a pod disruption budget with the specified name.
  priorityclass       Create a priorityclass with the specified name.
  quota               Create a quota with the specified name.
  role                Create a role with single rule.
  rolebinding         Create a RoleBinding for a particular Role or ClusterRole
  secret              Create a secret using specified subcommand
  service             Create a service using specified subcommand.
  serviceaccount      Create a service account with the specified name

(...)

Posted on 14/01/2021