patch a configmap from file or with json

8/18/2019

I want to edit a configmap from aws-auth during a vagrant deployment to give my vagrant user access to the EKS cluster. I need to add a snippet into the existing aws-auth configmap. How do i do this programmatically?

If you do a kubectl edit -n kube-system configmap/aws-auth you get

apiVersion: v1
data:
  mapRoles: |
    - groups:
      - system:bootstrappers
      - system:nodes
      rolearn: arn:aws:iam::123:role/nodegroup-abc123
      username: system:node:{{EC2PrivateDNSName}}
kind: ConfigMap
metadata:
  creationTimestamp: "2019-05-30T03:00:18Z"
  name: aws-auth
  namespace: kube-system
  resourceVersion: "19055217"
  selfLink: /api/v1/namespaces/kube-system/configmaps/aws-auth
  uid: 0000-0000-0000

i need to enter this bit in there somehow.

  mapUsers: |
    - userarn: arn:aws:iam::123:user/sergeant-poopie-pants
      username: sergeant-poopie-pants
      groups:
      - system:masters

I've tried to do a cat <<EOF > {file} EOF then patch from file. But that option doesn't exist in patch only in the create context.

I also found this: How to patch a ConfigMap in Kubernetes

but it didn't seem to work. or perhaps i didn't really understand the proposed solutions.

-- Eli
aws-eks
configmap
kubernetes

2 Answers

8/18/2019

First, note that the mapRoles and mapUsers are actually treated as a string, even though it is structured data (yaml).

While this problem is solvable by jsonpatch, it is much easier using jq and kubectl apply like this:

kubectl get cm aws-auth -o json \
  | jq --arg add "`cat add.yaml`" '.data.mapUsers = $add' \
  | kubectl apply -f -

Where add.yaml is something like this (notice the lack of extra indentation):

- userarn: arn:aws:iam::123:user/sergeant-poopie-pants
  username: sergeant-poopie-pants
  groups:
  - system:masters

See also https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html for more information.

-- Janos Lenart
Source: StackOverflow

8/18/2019

There are a few ways to automate things. The direct way would be kubectl get configmap -o yaml ... > cm.yml && patch ... < cm.yml > cm2.yml && kubectl apply -f cm2.yml or something like that. You might want to use a script that parses and modifies the YAML data rather than a literal patch to make it less brittle. You could also do something like EDITOR="myeditscript" kubectl edit configmap ... but that's more clever that I would want to do.

-- coderanger
Source: StackOverflow