在 github 操作中保留 k8s 的秘密

时间:2021-03-29 15:20:32

标签: json go github kubernetes github-actions

我们正在尝试使用github actions,我们希望将kubeconfig等敏感数据保存在github secrets 我创建了一个名为 KUBECONFIG1

的 GitHub 机密

重现步骤

在 GitHub 秘密中我应该存储以下文件也尝试使用此 https://onlineyamltools.com/convert-yaml-to-json 转换为 JSON

apiVersion: v1
kind: Config
clusters:
  - name: brf
    cluster:
      certificate-authority-data: >-
        LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURTakNBd0t6RXBNQ2NHQTFVRUF4TWdkbWx5ZE2bUljTlRtakFWCi0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0=
      server: 'https://vfg.canary.k8s.ondemand.com'
users:
  - name: user1
    user:
      token: >-
        eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuW1lc3BhY2UiOiJnYXJkZW4tZGV2e
contexts:
  - name: g-root
    context:
      cluster: garv
      user: robot
      namespace: gking
current-context: gaot

在 github 操作工作流中,我们使用名称 KUBECONFIG1 保留上面的文件内容,并从中创建 k8s 机密。

name: Example action

on: [push]

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v2
      - name: install k8s
        run: |
          curl -sfL https://get.k3s.io | K3S_KUBECONFIG_MODE=777 sh -
          cat /etc/rancher/k3s/k3s.yaml
          mkdir -p ~/.kube
          cp /etc/rancher/k3s/k3s.yaml ~/.kube/config


     - run: 'echo -e "$KUBECONFIG1" > ~/.tmpfile.json'
        shell: bash
        env:
          KUBECONFIG1: ${{secrets.KUBECONFIG1}}
    
      - name: example 
        shell: bash
        run: |
          cd ~/
          kubectl create secret generic project-kubecfg --from-file=~/.tmpfile.json -n default

运行此工作流程后,我收到以下错误:

error: error loading config file "/home/runner/work/_temp/kubeconfig_1617030542039": couldn't get version/kind; json parse error: json: cannot unmarshal string into Go value of type struct *** APIVersion string "json:\"apiVersion,omitempty\""; Kind string "json:\"kind,omitempty\"" ***
Error: Process completed with exit code 1.

我也尝试获取文件内容并使用 https://onlinelinuxtools.com/escape-shell-characters

当我们使用 Golang 时,也许我应该使用 kubeconfig 并将其用作 go 模板,并将 sensitive-data 之类的 token certificate-authority-data 等保存为 github 机密,并在工作流程中更新机密对模板的价值,但不确定如何...

我最后需要什么我需要以下命令在工作流程中起作用

kubectl create secret generic project-kubecfg --from-file=~/.tmpfile.json -n default

1 个答案:

答案 0 :(得分:1)

问题在于以下命令

kubectl create secret generic project-kubecfg --from-file=~/.tmpfile.json -n default

问题是 ~ 转到 kubectl 并没有将其扩展到主目录。因此,如果您像下面那样更改它,它将起作用

kubectl create secret generic project-kubecfg --from-file=/home/runner/.tmpfile.json -n default

或者使用固定路径而不是带有 ~ 的主目录