how to change a clusterrole with kubectl gracefully

9/23/2019

by default, the data in clusterrole system:node is as below:

$ kubectl get clusterrole system:node -o yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
name: system:node
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - create
  - delete
- apiGroups:
  - ""
  resources:
  - pods/status
  verbs:
  - patch
  - update

Now, I want to change the clusterrole system:node, add a - patch under the pods resources, it shoue be like this:

- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
  - list
  - watch
  - patch

I could update it by using kubectl edit, but I want to update it in the bash script, so kubectl edit is not suitable, is there any other solution by using kubectl?

-- kins
kubernetes

3 Answers

9/23/2019

Probably, the simplest automatable way is to add a new rule to the ClusterRole.

Create a file named append.yaml with the following content:

- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - patch

Then, append this rule to the existing YAML manifest of the ClusterRole and reapply it with:

kubectl apply -f <(cat <(kubectl get clusterrole system:node -o yaml) append.yaml)

The new rule will be merged with the other permissions for pods, which you can verify with:

kubectl describe clusterrole system:node

The nicest imperative solution would be to patch the object with kubectl patch, but it doesn't seem to be easily possible:

  • If you want to use a strategic patch: the rules array of the ClusterRole object seems to use a replace patch strategy, that is, the provided patch would just replace the existing array rather being merged with it.
  • If you want to use a JSON patch to add an additional rule: it doesn't seem to be possible to add a deeply structured array element to an existing array.
-- weibeld
Source: StackOverflow

9/23/2019

chages.yaml

rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
  - list
  - watch
  - patch #added
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - create
  - delete
- apiGroups:
  - ""
  resources:
  - pods/status
  verbs:
  - patch
  - update

Use the following bash command to update the ClusterRole

kubectl patch clusterrole system:node  --patch "$(cat changes.yaml)" 

For more details visit k8s official documentations

-- Kamol Hasan
Source: StackOverflow

9/23/2019

You can use a kubectl apply -f node-role.yaml where node-role.yaml contains the yaml definition of the ClusterRole with your change included. kubectl apply will update the role if it already exists (and create it otherwise).

-- Blokje5
Source: StackOverflow