add only docker registry auths to docker config

This commit is contained in:
Aishwarya Lad
2024-06-24 12:50:00 -07:00
parent e9b38c94b4
commit ced9875ed0
4 changed files with 79 additions and 30 deletions
+1 -3
View File
@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/pkg/errors"
@@ -54,7 +53,7 @@ func (c *Config) SetCredHelper(registry, helper string) {
func (c *Config) CreateDockerConfigJson(credentials []RegistryCredentials) ([]byte, error) {
for _, cred := range credentials {
if cred.Registry != "" {
if cred.Registry != "" && strings.Contains(cred.Registry, "docker") {
if cred.Username == "" {
return nil, fmt.Errorf("Username must be specified for registry: %s", cred.Registry)
@@ -67,7 +66,6 @@ func (c *Config) CreateDockerConfigJson(credentials []RegistryCredentials) ([]by
}
jsonBytes, err := json.Marshal(c)
log.Printf("jsonBytes config : %s", jsonBytes)
if err != nil {
return nil, errors.Wrap(err, "failed to serialize docker config json")
}
+64
View File
@@ -0,0 +1,64 @@
package docker
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
const (
RegistryV1 string = "https://index.docker.io/v1/"
RegistryV2 string = "https://index.docker.io/v2/"
RegistryECRPublic string = "public.ecr.aws"
)
func TestConfig(t *testing.T) {
c := NewConfig()
assert.NotNil(t, c.Auths)
assert.NotNil(t, c.CredHelpers)
c.SetAuth(RegistryV1, "test", "password")
expectedAuth := Auth{Auth: "dGVzdDpwYXNzd29yZA=="}
assert.Equal(t, expectedAuth, c.Auths[RegistryV1])
c.SetCredHelper(RegistryECRPublic, "ecr-login")
assert.Equal(t, "ecr-login", c.CredHelpers[RegistryECRPublic])
tempDir, err := ioutil.TempDir("", "docker-config-test")
assert.NoError(t, err)
defer os.RemoveAll(tempDir)
credentials := []RegistryCredentials{
{
Registry: "https://index.docker.io/v1/",
Username: "user1",
Password: "pass1",
},
{
Registry: "gcr.io",
Username: "user2",
Password: "pass2",
},
}
jsonBytes, err := c.CreateDockerConfigJson(credentials)
assert.NoError(t, err)
configPath := filepath.Join(tempDir, "config.json")
err = ioutil.WriteFile(configPath, jsonBytes, 0644)
assert.NoError(t, err)
data, err := ioutil.ReadFile(configPath)
assert.NoError(t, err)
var configFromFile Config
err = json.Unmarshal(data, &configFromFile)
assert.NoError(t, err)
assert.Equal(t, c.Auths, configFromFile.Auths)
assert.Equal(t, c.CredHelpers, configFromFile.CredHelpers)
}