kubernetesgithub-actionscicdkubeconfiggithub-secret

Github Actions: How to store kubeconfig in github secrets


I have this kubeconfig file

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: ***
    server: ***
  name: ***
contexts:
- context:
    cluster: ***
    user: webhook
  name: *****
current-context: *****
kind: Config
preferences: {}
users:
- name: webhook
  user:
    token: ${MY_APIKEY}

I am storing it in secret in github that is named DEV_CLUSTER_KUBECONF

I am also storing MY_APIKEY in GitHub secrets

Then I have this actions workflow file whose purpose is the write the content into a file and then populate it with a token coming form github actions.

name: wfl

on:
  push:
env:
  DEV_CLUSTER_KUBECONF: ${{ secrets.DEV_CLUSTER_KUBECONF }}

jobs:
  j1:
    needs: build
    runs-on: ....
    container:
      image: .....
    steps:
      - name: pull kubeconfig
        run: |
          mkdir kubeconf
          touch kubeconf.conf
          echo $DEV_CLUSTER_KUBECONF >> kubeconf/kubeconf.conf

      - name: envsub kube.conf
        run: |
          cat kubeconf/kubeconf.conf | envsubst > populated_kube.conf
        env:
          MY_APIKEY: ${{ secrets.MY_APIKEY }}
      - name: export KUBECONFIG path
        run: echo "KUBECONFIG=populated_kube.conf" >> $GITHUB_ENV
      - name: kubectl
        run: kubectl get po

This is a simplified version of my work. I prefer to keep it three steps. I mean I want to store the kubeconfig with the api key placeholder separate from the api key in the github secrets.

However, right now it is not connecting to k8s.

I used to keep kubeconf/kubeconf.conf in the repo and after checkout, do the envsubt on that file and it was working. I am not sure why it is not working now. seems like kubeconf/kubeconf.conf is not correct but when I try to print it and debug it is showing *******.

Any idea how to fix this?


Solution

  • You need to properly quote your variables. Consider what happens if I create a multiline environment variable:

    MVAR='this
    is
    a
    test'
    

    And then try to echo it without using quotes:

    $ echo $MYVAR
    this is a test
    

    Compare that to the result when using quotes:

    $ echo "$MYVAR"
    this
    is
    a
    test
    

    So you need to edit your action to read:

          - name: pull kubeconfig
            run: |
              mkdir kubeconf
              echo "$DEV_CLUSTER_KUBECONF" > kubeconf/kubeconf.conf
    

    (I've removed an unnecessary touch kubeconf.conf here, because that wasn't creating the file in the correct path and wasn't necessary in any case.)

    If that doesn't work, the first thing you should do is add a cat kubeconf/kubeconf.conf to your workflow so you can inspect the generated file.