How to generate yaml template with kubectl command?

8/28/2019

Is it possible to generate yaml with kubernetes kubectl command ? to clarify - I'm not talking about generating yaml from existing deployments like kubectl get XXXX -o yaml, but merely about generating yamls for the very first time for pod, service, ingress, etc.

PS There is a way to get yaml files from kubernetes.io site ( 1 , 2 ) but I am looking if there is a way to generate yamls templates with kubectl only.

-- Andy
docker
kubectl
kubernetes
yaml

1 Answer

8/28/2019

There's the command create in kubectl that does the trick and replaced the run used in the past: let's image you want to create a Deployment running a nginx:latest Docker image.

# kubectl create deployment my_deployment --image=busybox --dry-run=true --output=yaml

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

Let's analyze each parameter:

  • my_deployment is the Deployment name you chose
  • --image is the Docker image you want to deploy
  • --dry-run=true won't execute the resource creation, used mainly for validation
  • --output=yaml prints to standard output the YAML definition of the Deployment resource.

Obviously, you can perform this options just with few Kubernetes default resources:

# kubectl create 
  clusterrole         Create a ClusterRole.
  clusterrolebinding  Create a ClusterRoleBinding for a particular ClusterRole
  configmap           Create a configmap from a local file, directory or literal value
  deployment          Create a deployment 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

According to this, you can render the template without the prior need of deploying your resource.

-- prometherion
Source: StackOverflow