Search code examples
kuberneteskubectlkubeconfig

Merging kubeconfig JSON and YAML


I have two kubeconfigs file, the first one is following which I use to communicate with the cluster and the second one is for Aquasec which is in JSON format. How can I merge these two?

apiVersion: v1
    clusters:
    - cluster:
        certificate-authority-data: DATA+OMITTED
        server: https://656835E69F31E2933asdAFAKE3F5904sadFDDC112dsasa7.yld432.eu-west-2.eks.amazonaws.com
      name: arn:aws:eks:eu-west-2:test651666:cluster/Magento
    - cluster:
        certificate-authority-data: DATA+OMITTED
        server: https://kubernetes.docker.internal:6443
      name: docker-desktop
    - cluster:
        certificate-authority-data: DATA+OMITTED
        server: https://192.142.242.111:6443
      name: kubernetes
    contexts:
    - context:
        cluster: arn:aws:eks:eu-west-2:test651666:cluster/testing
        user: arn:aws:eks:eu-west-2:test651666:cluster/testing
      name: arn:aws:eks:eu-west-2:test651666:cluster/testing
    - context:
        cluster: docker-desktop
        user: docker-desktop
      name: docker-desktop
    - context:
        cluster: docker-desktop
        user: docker-desktop
      name: docker-for-desktop
    - context:
        cluster: kubernetes
        user: kubernetes-admin
      name: kubernetes-admin@kubernetes
    current-context: arn:aws:eks:eu-west-2:test651666:cluster/testing
    kind: Config
    preferences: {}
    users:
    - name: arn:aws:eks:eu-west-2:test651666:cluster/testing

Solution

  • You can set the KUBECONFIG environment variable to multiple config files delimited by : and kubectl will automatically merge them behind the scenes.

    For example:

    export KUBECONFIG=config:my-config.json
    

    In the export above, config is the default config file contained within ~/.kube and my-config.json would be your second config file, which you said is in JSON format.

    You can see the merged config using this command, which shows a unified view of the configuration that kubectl is currently using:

    kubectl config view
    

    Because kubectl automatically merges multiple configs, you shouldn't need to save the merged config to a file. But if you really want to do that, you can redirect the output, like this:

    kubectl config view --flatten > merged-config.yaml
    

    Check out Mastering the KUBECONFIG file, Organizing Cluster Access Using kubeconfig Files for more explanation and to see some other examples.