Search code examples
kuberneteskubectl

How Can You Perform Variable Substitution using Kubectl?


I am trying to create a Role and RoleBinding so I can use Helm. I want to use variable substitution somehow to replace {{namespace}} with something when I run an apply command.

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: tiller-manager-{{namespace}}
  namespace: {{namespace}}
rules:
- apiGroups: ["", "batch", "extensions", "apps"]
  resources: ["*"]
  verbs: ["*"]

I want to pass the namespace something like this:

kubectl apply --file role.yaml --namespace foo

I have seen that kubectl apply has a --template parameter but I can't see much information about how it might be used.


Solution

  • You can do it in following way.

    1. Write Role file like this:

      kind: Role
      apiVersion: rbac.authorization.k8s.io/v1
      metadata:
        name: tiller-manager-${NAMESPACE}
        namespace: ${NAMESPACE}
      rules:
      - apiGroups: ["", "batch", "extensions", "apps"]
        resources: ["*"]
        verbs: ["*"]
      
    2. Set NAMESPACE environment variable to your desired value.

    3. Then create Role using following command

      envsubst < role.yaml | kubectl apply -f -