如何使用 client-go 创建 docker Secret

How to create docker Secret with client-go

假设我知道以下秘密参数:

"name":            "aaa",
"docker-server":   "a.b.com",
"docker-username": "aaa",
"docker-password": "aaaa",
"docker-email":    "aaa@gmail.com"

那我想用client-go创建pull-image secret

secret := &corev1.Secret{
    ObjectMeta: metav1.ObjectMeta{
        Name:      "pull-image-secret",
        Namespace: "aaaaaa",
    },
    Type: "kubernetes.io/dockerconfigjson",
    Data: map[string][]byte{".dockerconfigjson": []byte(secretData)},
}
err = k8sClient.Create(context.Background(), secret)

我的问题是,如何将secret参数转换成secretData?

来自docs

the data field of the Secret object must contain a .dockerconfigjson key, in which the content for the ~/.docker/config.json file is provided as a base64 encoded string

所以如果你想使用 Data 字段你需要修改代码以 base64 编码秘密数据,类似的东西应该可以工作:

import b64 "encoding/base64"

...

base64EncodedData := make([]byte, b64.StdEncoding.EncodedLen(len(secretData)))
b64.StdEncoding.Encode(base64EncodedData, []byte(secretData))

secret := &corev1.Secret{
    ObjectMeta: metav1.ObjectMeta{
        Name:      "pull-image-secret",
        Namespace: "aaaaaa",
    },
    Type: "kubernetes.io/dockerconfigjson",
    Data: map[string][]byte{".dockerconfigjson": base64EncodedData},
}

否则,你可以尝试使用不带base64编码的StringData字段:

secret := &corev1.Secret{
    ObjectMeta: metav1.ObjectMeta{
        Name:      "pull-image-secret",
        Namespace: "aaaaaa",
    },
    Type: "kubernetes.io/dockerconfigjson",
    StringData: map[string]string{".dockerconfigjson": secretData},
}