How Can You Perform Variable Substitution using Kubectl?

11/13/2018

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.

-- Muhammad Rehan Saeed
kubectl
kubernetes

2 Answers

11/13/2018

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 -
-- Emruz Hossain
Source: StackOverflow

11/15/2018

Another way you can use. With sed command you can replace {{namespace}} directly. without setting any environment variable or using envsubst.

  1. First save your role in a file say role.yaml which contains original content.
  2. Then use sed 's/{{namespace}}/your-namespace-name/g' role.yaml. which print in stdout the desired file. Replaced {{namespace}} with your-namespace-name.

N.B: you can also save it in a file using sed 's/{{namespace}}/your-namespace-name/g' role.yaml > new-role.yaml

-- Abu Hanifa
Source: StackOverflow