Joe
Joe

Reputation: 693

How to create docker Secret with client-go

Assume I know the following secret parameters:

"name":            "aaa",
"docker-server":   "a.b.com",
"docker-username": "aaa",
"docker-password": "aaaa",
"docker-email":    "[email protected]"

Then I want to use client-go to create a 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)

My question is, how to convert secret parameters into secretData?

Upvotes: 2

Views: 3072

Answers (2)

tpoxa
tpoxa

Reputation: 101

You don't need to encode secret data with base64. K8s does it for you. And I think the question was about how to exactly create secret data itself.

I did something like this:

type DockerRegistryConfig struct {
    Auths map[string]DockerRegistryAuth `json:"auths"`
}

type DockerRegistryAuth struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

conf := containers.DockerRegistryConfig{
    Auths: map[string]containers.DockerRegistryAuth{
        "registry.gitlab.com": {
            Username: "gitlab+deploy-token",
            Password: "",
        },
    },
}
secretData, _ := json.Marshal(conf)

Upvotes: 0

Grigoriy Mikhalkin
Grigoriy Mikhalkin

Reputation: 5573

From 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

So if you want to use Data field you need to modify code to base64 encode secret data, something like that should work:

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},
}

Otherwise, you can try to use StringData field without base64 encoding:

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

Upvotes: 2

Related Questions