Search code examples
powershellkubectl

Run `kubectl apply` using yaml stored in a variable


I have a resource I want to apply as part of an automated script (running in powershell). I would rather not have to write it out to a file then have to deal with cleaning it up.

Is it possible to apply the yaml as part of a script?

Something similar to this:

$myYaml = @'
apiVersion: "rbac.authorization.k8s.io/v1"
kind: RoleBinding
metadata:
  name: ServiceAccount-clusteradmin
roleRef:
  apiGroup: "rbac.authorization.k8s.io"
  kind: ClusterRole
  name: ClusterAdmin
subjects:
  - apiGroup: "rbac.authorization.k8s.io"
    kind: User
    name: "MyAdminServiceAccount"
'@

kubectl apply @myYaml

Clearly, the kubectl command above does not work.

My question is: Is a way to apply this yaml without creating a file (using powershell)?


Solution

  • myYaml is a variable having the data:

    $myYaml = @'
    apiVersion: "rbac.authorization.k8s.io/v1"
    kind: RoleBinding
    metadata:
      name: ServiceAccount-clusteradmin
    roleRef:
      apiGroup: "rbac.authorization.k8s.io"
      kind: ClusterRole
      name: ClusterAdmin
    subjects:
      - apiGroup: "rbac.authorization.k8s.io"
        kind: User
        name: "MyAdminServiceAccount"
    '@
    

    Perform the following to echo the contents of $myYaml variable and pipe it to kubectl apply -f -, here last - is for piped input.

    $myYaml |kubectl.exe apply -f -
    rolebinding.rbac.authorization.k8s.io/ServiceAccount-clusteradmin created
    
    kubectl.exe get rolebindings
    NAME                          ROLE                       AGE
    ServiceAccount-clusteradmin   ClusterRole/ClusterAdmin   18s
    

    This is very similar to linux environment where echo "$var" |kubectl apply -f - is used to perform same action.