WriteCertsForRegistry writes the certificates found in the provided directory to the correct subdirectory that the Docker daemon uses when pulling images from the specified private registry.
(ctx context.Context, registryName, certsDir string)
| 15 | // to the correct subdirectory that the Docker daemon uses when pulling images |
| 16 | // from the specified private registry. |
| 17 | func WriteCertsForRegistry(ctx context.Context, registryName, certsDir string) error { |
| 18 | fs := xunix.GetFS(ctx) |
| 19 | |
| 20 | // Docker certs directory. |
| 21 | registryCertsDir := filepath.Join("/etc/docker/certs.d", registryName) |
| 22 | |
| 23 | // If the directory already exists it means someone |
| 24 | // has either wrapped the image or has mounted in certs |
| 25 | // manually. We should assume the user knows what they're |
| 26 | // doing and avoid mucking with their solution. |
| 27 | if _, err := fs.Stat(registryCertsDir); err == nil { |
| 28 | return nil |
| 29 | } |
| 30 | |
| 31 | // Ensure the registry certs directory exists. |
| 32 | err := fs.MkdirAll(registryCertsDir, 0o755) |
| 33 | if err != nil { |
| 34 | return xerrors.Errorf("create registry certs directory: %w", err) |
| 35 | } |
| 36 | |
| 37 | // Check if certsDir is a file. |
| 38 | fileInfo, err := fs.Stat(certsDir) |
| 39 | if err != nil { |
| 40 | return xerrors.Errorf("stat certs directory/file: %w", err) |
| 41 | } |
| 42 | |
| 43 | if !fileInfo.IsDir() { |
| 44 | // If it's a file, copy it directly |
| 45 | err = copyCertFile(fs, certsDir, filepath.Join(registryCertsDir, "ca.crt")) |
| 46 | if err != nil { |
| 47 | return xerrors.Errorf("copy cert file: %w", err) |
| 48 | } |
| 49 | return nil |
| 50 | } |
| 51 | |
| 52 | // If it's a directory, copy all cert files in the root of the directory |
| 53 | entries, err := afero.ReadDir(fs, certsDir) |
| 54 | if err != nil { |
| 55 | return xerrors.Errorf("read certs directory: %w", err) |
| 56 | } |
| 57 | |
| 58 | for _, entry := range entries { |
| 59 | if entry.IsDir() { |
| 60 | continue |
| 61 | } |
| 62 | srcPath := filepath.Join(certsDir, entry.Name()) |
| 63 | dstPath := filepath.Join(registryCertsDir, entry.Name()) |
| 64 | err = copyCertFile(fs, srcPath, dstPath) |
| 65 | if err != nil { |
| 66 | return xerrors.Errorf("copy cert file %s: %w", entry.Name(), err) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | return nil |
| 71 | } |
| 72 | |
| 73 | func copyCertFile(fs xunix.FS, src, dst string) error { |
| 74 | srcFile, err := fs.Open(src) |