Compare commits

...

20 Commits

Author SHA1 Message Date
Devansh Mathur d6153866df feat: [CI-16330]: Adding default OutputFile as DRONE_OUTPUT. (#139)
* Adding default OutputFile as DRONE_OUTPUT.

* Removing if checks and optimizing setting up of default OutputFile as DRONE_OUTPUT.
2025-03-03 18:05:21 +05:30
OP (oppenheimer) 30e1ea9fd8 Update main.go (#138) 2025-02-07 14:28:32 +05:30
OP (oppenheimer) 0fb726616e feat: [CI-16193]: Support multiple ignore paths (#137)
* add new input ignore_paths to accept multiple values

* Support new input ignore_paths to all the supported versions of Kaniko
2025-02-07 11:46:23 +05:30
OP (oppenheimer) 334f6191d1 Add Push-only support to Kaniko (Docker) (#135) 2024-12-20 11:17:28 +05:30
sahithibanda01 a3af953651 fix: [CI-14845]: support for build args which has comma seperated values (#133) 2024-11-29 13:12:39 +05:30
Anshika Anand e6ab8aa3c0 feat:[CI-15236]: Added IMAGE_TAR_PATH as output variable for the plugin. (#132)
* feat:[CI-15236]: Added PLUGIN_TAR_PATH as output variable for the plugin.

* feat:[CI-15236]: Added PLUGIN_TAR_PATH as output variable for the plugin.

* feat:[CI-15236]: Added PLUGIN_TAR_PATH as output variable for the plugin.

* feat:[CI-15236]: Added PLUGIN_TAR_PATH as output variable for the plugin.

* feat:[CI-15236]: Test commit.

* feat:[CI-15236]: Test commit.

* feat:[CI-15236]: Added PLUGIN_TAR_PATH as output variable for the plugin.

* feat:[CI-15236]: Directory check and UTs.

* Update pkg/output/output.go

* feat:[CI-15236]: fixes

* feat:[CI-15236]: Test fixes - removed root

* feat:[CI-15236]: Test fixes - removed root

* feat:[CI-15236]: Test fixes - removed root

* feat:[CI-15236]: If tarPath directory no present it will create it.

* feat:[CI-15236]: If tarPath directory no present it will create it.

* feat:[CI-15236]: fixes

* Update kaniko.go

removed as getTarPath is only called when tarPath isn't empty

---------

Co-authored-by: OP (oppenheimer) <21008429+Ompragash@users.noreply.github.com>
2024-11-28 18:31:10 +05:30
Abhay 113a61b0e1 feat: [Ci-14242]: add oidc support for ecr (#131)
* feat: [Ci-14242]: add oidc support for ecr

* fix: [CI-14242]: error handling for oidc kakniko-ecr
2024-10-17 01:51:09 +05:30
rahkumar56 982c141391 feat: [CI-13961]: Upgraded gcr.io/kaniko-project/executor version to v1.23.2. (#125) 2024-09-09 11:23:40 +05:30
Aishwarya Lad f41d7cb836 upgrade kaniko version for chmod on ADD and COPY (#121) 2024-07-10 19:44:09 +05:30
rahkumar56 a71177d4b4 fix: [CI-13178]: Upgrade go version with minor version to 1.22.4 (#120) 2024-07-10 16:06:42 +05:30
rahkumar56 5582e3ed7c feat: [CI-13178]: GO version upgrade from 1.22.0 to 1.22.4. (#119) 2024-07-03 12:30:41 +05:30
Hemanth Mantri 4c0f781999 [CI-13182]: Use snapshot-mode instead of snapshotMode (#118)
The kaniko flag `snapshotMode` is deprecated in favor of `snapshot-mode`. The default value of `snapshot-mode` is `full`. As a result, the `optimize` flag set in Harness CI's `BuildAndPushToDocker` steps doesn't behave as expected because the `full` mode triggers a full filesystem scan which is slow. The `optimize` flag in Harness translates to `snapshot-mode=redo` which means only filesystem deltas are compared which is much faster. 

This change fixes the flag name being sent to Kaniko executor. I verified that the executor present in the current version already supports this flag as shown below:

```
hemanthkumarmantri@Hemanth Kumar harness-core % docker run -it --entrypoint /kaniko/executor plugins/kaniko:1.8.10 --help | grep snapshot-mode
      --snapshot-mode string                      Change the file attributes inspected during snapshotting (default "full")
      --snapshotMode string                       This flag is deprecated. Please use '--snapshot-mode'.
```
2024-07-01 14:06:19 -07:00
Abhay 20525e5403 feat: [CI-10849]: add git-leaks support (#113)
* feat: [CI-10849]: add git-leaks support

* correct reference
2024-05-10 12:38:31 +01:00
Aishwarya Lad 04885c8ec8 fix tests (#117) 2024-05-01 15:14:04 -04:00
Aishwarya Lad e4a0486a6e modify base image registry variable (#116)
* modify base image registry variable

* adding instead of modifying

* adding instead of modifying
2024-04-29 14:26:31 -04:00
Aishwarya Lad 7b442a53ff Modify docker config to add base connector (#115)
* add config for base connector

* fix permissions code

* add gar step support

* add gar step support

* reformat code, add support for gar and acr

* remove logs

* address review comments

* delete bin file
2024-04-26 15:54:08 -04:00
Abhay f224543240 fix: [CI-11358]: fix kaniko executor Vulnerabilities (#114) 2024-03-20 12:57:59 +05:30
rahkumar56 910bcb89c2 Update GO Version to latest version in all the files (#112) 2024-03-05 23:15:25 +05:30
Soumyajit Das 44ccf5a7c6 fix: [CI-10165]: Add additional kaniko args (#102)
* fix: [CI-10165]: Add additional kaniko args

* fix: [CI-10165]: support additional kaniko args

* fix: [CI-10165]: Add bool parse logic
2024-02-06 15:22:31 +05:30
Rojan Dinc f8c678fcde Revert "fix: [CI-10165]: support additional kaniko args from PLUGIN_ env vars (#93)" (#99)
This reverts commit 20c593c3e7.
2024-01-30 21:33:04 +05:30
38 changed files with 2877 additions and 531 deletions
+2 -2
View File
@@ -11,7 +11,7 @@ platform:
steps:
- name: build
image: golang:1.21
image: golang:1.22.4
commands:
- go test ./...
- sh scripts/build.sh
@@ -178,7 +178,7 @@ pool:
steps:
- name: build
image: golang:1.21
image: golang:1.22.4
commands:
- go test ./...
- sh scripts/build.sh
+40 -2
View File
@@ -4,6 +4,13 @@ Drone kaniko plugin uses [kaniko](https://github.com/GoogleContainerTools/kaniko
Plugin images are published with 1.6.0 as well as 1.9.1 kaniko version from 1.5.1 release tag. `plugins/kaniko:<release-tag>` uses 1.6.0 version while `plugins/kaniko:<release-tag>-kaniko1.9.1` uses 1.9.1 version. Similar convention is used for plugins/kaniko-ecr & plugins/kaniko-gcr images as well.
Run the following script to install git-leaks support to this repo.
```
chmod +x ./git-hooks/install.sh
./git-hooks/install.sh
```
## Build
Build the binaries with the following commands:
@@ -29,7 +36,7 @@ docker build \
--label org.label-schema.build-date=$(date -u +"%Y-%m-%dT%H:%M:%SZ") \
--label org.label-schema.vcs-ref=$(git rev-parse --short HEAD) \
--file docker/docker/Dockerfile.linux.amd64 --tag plugins/kaniko .
docker build \
--label org.label-schema.build-date=$(date -u +"%Y-%m-%dT%H:%M:%SZ") \
--label org.label-schema.vcs-ref=$(git rev-parse --short HEAD) \
@@ -47,6 +54,33 @@ docker build \
```
## Usage
### Operation Modes
Default Mode (Build and Push):
When neither `no_push` nor `push_only` is provided. Plugin builds and pushes the Docker image to a container registry.
Build-Only Mode (no-push):
When `no_push` is true and `destination_tar_path` is defined.
Plugin performs only the image build operation and saves the resulting image tarball to the specified `destination_tar_path`
It does not push the image to any registry.
Push-Only Mode (push-only):
When `push_only` is true and `source_tar_path` is defined.
Plugin loads an existing image tarball from the specified `source_tar_path`
and pushes the loaded image to a Container Registry.
It skips the build process.
### Mutually Exclusive Inputs
If both `no_push` and `push_only` inputs are provided, the plugin will:
Terminate the operation and
throw an error with the message: "Inputs no-push and push-only cannot be used together. Please define only one."
### Manual Tagging
```console
@@ -73,6 +107,7 @@ docker run --rm \
-w /drone \
plugins/kaniko:linux-amd64
```
would both be equivalent to
```
@@ -82,7 +117,7 @@ PLUGIN_TAGS=1,1.2,1.2.3,latest
This allows for passing `$DRONE_TAG` directly as a tag for repos that use [semver](https://semver.org) tags.
To avoid confusion between repo tags and image tags, `PLUGIN_EXPAND_TAG` also recognizes a semantic version
without the `v` prefix. As such, the following is also equivalent to the above:
without the `v` prefix. As such, the following is also equivalent to the above:
```console
docker run --rm \
@@ -94,6 +129,7 @@ docker run --rm \
```
### Auto Tagging
The [auto tag feature](https://plugins.drone.io/drone-plugins/drone-docker) of docker plugin is also supported.
When auto tagging is enabled, if any of the case is matched below, a docker build will be pushed with auto generated tags. Otherwise the docker build will be skipped.
@@ -115,6 +151,7 @@ docker run --rm \
```
Tags to push:
- 1.2.3
- 1.2
- 1
@@ -135,4 +172,5 @@ docker run --rm \
```
Tags to push:
- latest
+254 -27
View File
@@ -23,12 +23,11 @@ import (
)
const (
dockerPath string = "/kaniko/.docker"
clientIdEnv string = "AZURE_CLIENT_ID"
clientSecretKeyEnv string = "AZURE_CLIENT_SECRET"
dockerConfigPath string = "/kaniko/.docker"
tenantKeyEnv string = "AZURE_TENANT_ID"
certPathEnv string = "AZURE_CLIENT_CERTIFICATE_PATH"
dockerConfigPath string = "/kaniko/.docker"
defaultDigestFile string = "/kaniko/digest-file"
finalUrl string = "https://portal.azure.com/#view/Microsoft_Azure_ContainerRegistries/TagMetadataBlade/registryId/"
)
@@ -122,6 +121,21 @@ func main() {
Usage: "ACR registry",
EnvVar: "PLUGIN_REGISTRY",
},
cli.StringFlag{
Name: "base-image-registry",
Usage: "Docker registry for base image",
EnvVar: "PLUGIN_DOCKER_REGISTRY,PLUGIN_BASE_IMAGE_REGISTRY,DOCKER_REGISTRY",
},
cli.StringFlag{
Name: "base-image-username",
Usage: "Docker username for base image registry",
EnvVar: "PLUGIN_DOCKER_USERNAME,PLUGIN_BASE_IMAGE_USERNAME,DOCKER_USERNAME",
},
cli.StringFlag{
Name: "base-image-password",
Usage: "Docker password for base image registry",
EnvVar: "PLUGIN_DOCKER_PASSWORD,PLUGIN_BASE_IMAGE_PASSWORD,DOCKER_PASSWORD",
},
cli.StringSliceFlag{
Name: "registry-mirrors",
Usage: "docker registry mirrors",
@@ -207,6 +221,157 @@ func main() {
Usage: "build only used stages",
EnvVar: "PLUGIN_SKIP_UNUSED_STAGES",
},
cli.StringFlag{
Name: "cache-dir",
Usage: "Set this flag to specify a local directory cache for base images",
EnvVar: "PLUGIN_CACHE_DIR",
},
cli.BoolFlag{
Name: "cache-copy-layers",
Usage: "Enable or disable copying layers from the cache.",
EnvVar: "PLUGIN_CACHE_COPY_LAYERS",
},
cli.BoolFlag{
Name: "cache-run-layers",
Usage: "Enable or disable running layers from the cache.",
EnvVar: "PLUGIN_CACHE_RUN_LAYERS",
},
cli.BoolFlag{
Name: "cleanup",
Usage: "Enable or disable cleanup of temporary files.",
EnvVar: "PLUGIN_CLEANUP",
},
cli.BoolFlag{
Name: "compressed-caching",
Usage: "Enable or disable compressed caching.",
EnvVar: "PLUGIN_COMPRESSED_CACHING",
},
cli.StringFlag{
Name: "context-sub-path",
Usage: "Sub-path within the context to build.",
EnvVar: "PLUGIN_CONTEXT_SUB_PATH",
},
cli.StringFlag{
Name: "custom-platform",
Usage: "Platform to use for building.",
EnvVar: "PLUGIN_CUSTOM_PLATFORM",
},
cli.BoolFlag{
Name: "force",
Usage: "Force building the image even if it already exists.",
EnvVar: "PLUGIN_FORCE",
},
cli.StringSliceFlag{
Name: "image-name-with-digest-file",
Usage: "Write image name with digest to a file.",
EnvVar: "PLUGIN_IMAGE_NAME_WITH_DIGEST_FILE",
},
cli.StringFlag{
Name: "image-name-tag-with-digest-file",
Usage: "Write image name with tag and digest to a file.",
EnvVar: "PLUGIN_IMAGE_NAME_TAG_WITH_DIGEST_FILE",
},
cli.BoolFlag{
Name: "insecure",
Usage: "Allow connecting to registries without TLS.",
EnvVar: "PLUGIN_INSECURE",
},
cli.BoolFlag{
Name: "insecure-pull",
Usage: "Allow insecure pulls from the registry.",
EnvVar: "PLUGIN_INSECURE_PULL",
},
cli.StringFlag{
Name: "insecure-registry",
Usage: "Use plain HTTP for registry communication.",
EnvVar: "PLUGIN_INSECURE_REGISTRY",
},
cli.StringFlag{
Name: "log-format",
Usage: "Set the log format for build output.",
EnvVar: "PLUGIN_LOG_FORMAT",
},
cli.BoolFlag{
Name: "log-timestamp",
Usage: "Show timestamps in build output.",
EnvVar: "PLUGIN_LOG_TIMESTAMP",
},
cli.StringFlag{
Name: "oci-layout-path",
Usage: "Directory to store OCI layout.",
EnvVar: "PLUGIN_OCI_LAYOUT_PATH",
},
cli.IntFlag{
Name: "push-retry",
Usage: "Number of times to retry pushing an image.",
EnvVar: "PLUGIN_PUSH_RETRY",
},
cli.StringFlag{
Name: "registry-certificate",
Usage: "Path to a file containing a registry certificate.",
EnvVar: "PLUGIN_REGISTRY_CERTIFICATE",
},
cli.StringFlag{
Name: "registry-client-cert",
Usage: "Path to a file containing a registry client certificate.",
EnvVar: "PLUGIN_REGISTRY_CLIENT_CERT",
},
cli.BoolFlag{
Name: "skip-default-registry-fallback",
Usage: "Skip Docker Hub and default registry fallback.",
EnvVar: "PLUGIN_SKIP_DEFAULT_REGISTRY_FALLBACK",
},
cli.BoolFlag{
Name: "reproducible",
Usage: "Create a reproducible image.",
EnvVar: "PLUGIN_REPRODUCIBLE",
},
cli.BoolFlag{
Name: "single-snapshot",
Usage: "Only create a single snapshot of the image.",
EnvVar: "PLUGIN_SINGLE_SNAPSHOT",
},
cli.BoolFlag{
Name: "skip-push-permission-check",
Usage: "Skip permission check when pushing.",
EnvVar: "PLUGIN_SKIP_PUSH_PERMISSION_CHECK",
},
cli.BoolFlag{
Name: "skip-tls-verify-pull",
Usage: "Skip TLS verification when pulling.",
EnvVar: "PLUGIN_SKIP_TLS_VERIFY_PULL",
},
cli.BoolFlag{
Name: "skip-tls-verify-registry",
Usage: "Skip TLS verification when connecting to a registry.",
EnvVar: "PLUGIN_SKIP_TLS_VERIFY_REGISTRY",
},
cli.BoolFlag{
Name: "use-new-run",
Usage: "Skip TLS verification when connecting to a registry.",
EnvVar: "PLUGIN_USE_NEW_RUN",
},
cli.BoolFlag{
Name: "ignore-var-run",
Usage: "Ignore the /var/run directory during build.",
EnvVar: "PLUGIN_IGNORE_VAR_RUN",
},
cli.StringFlag{
Name: "ignore-path",
Usage: "Path to ignore during the build.",
EnvVar: "PLUGIN_IGNORE_PATH",
},
cli.IntFlag{
Name: "image-fs-extract-retry",
Usage: "Number of retries for extracting filesystem layers.",
EnvVar: "PLUGIN_IMAGE_FS_EXTRACT_RETRY",
},
cli.IntFlag{
Name: "image-download-retry",
Usage: "Number of retries for downloading base images.",
EnvVar: "PLUGIN_IMAGE_DOWNLOAD_RETRY",
},
}
if err := app.Run(os.Args); err != nil {
@@ -225,6 +390,9 @@ func run(c *cli.Context) error {
c.String("client-secret"),
c.String("subscription-id"),
registry,
c.String("base-image-username"),
c.String("base-image-password"),
c.String("base-image-registry"),
noPush,
)
if err != nil {
@@ -233,28 +401,59 @@ func run(c *cli.Context) error {
plugin := kaniko.Plugin{
Build: kaniko.Build{
DroneCommitRef: c.String("drone-commit-ref"),
DroneRepoBranch: c.String("drone-repo-branch"),
Dockerfile: c.String("dockerfile"),
Context: c.String("context"),
Tags: c.StringSlice("tags"),
AutoTag: c.Bool("auto-tag"),
AutoTagSuffix: c.String("auto-tag-suffix"),
ExpandTag: c.Bool("expand-tag"),
Args: c.StringSlice("args"),
Target: c.String("target"),
Repo: c.String("repo"),
Mirrors: c.StringSlice("registry-mirrors"),
Labels: c.StringSlice("custom-labels"),
SnapshotMode: c.String("snapshot-mode"),
EnableCache: c.Bool("enable-cache"),
CacheRepo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("cache-repo")),
CacheTTL: c.Int("cache-ttl"),
DigestFile: defaultDigestFile,
NoPush: noPush,
Verbosity: c.String("verbosity"),
Platform: c.String("platform"),
SkipUnusedStages: c.Bool("skip-unused-stages"),
DroneCommitRef: c.String("drone-commit-ref"),
DroneRepoBranch: c.String("drone-repo-branch"),
Dockerfile: c.String("dockerfile"),
Context: c.String("context"),
Tags: c.StringSlice("tags"),
AutoTag: c.Bool("auto-tag"),
AutoTagSuffix: c.String("auto-tag-suffix"),
ExpandTag: c.Bool("expand-tag"),
Args: c.StringSlice("args"),
Target: c.String("target"),
Repo: c.String("repo"),
Mirrors: c.StringSlice("registry-mirrors"),
Labels: c.StringSlice("custom-labels"),
SnapshotMode: c.String("snapshot-mode"),
EnableCache: c.Bool("enable-cache"),
CacheRepo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("cache-repo")),
CacheTTL: c.Int("cache-ttl"),
DigestFile: defaultDigestFile,
NoPush: noPush,
Verbosity: c.String("verbosity"),
Platform: c.String("platform"),
SkipUnusedStages: c.Bool("skip-unused-stages"),
CacheDir: c.String("cache-dir"),
CacheCopyLayers: c.Bool("cache-copy-layers"),
CacheRunLayers: c.Bool("cache-run-layers"),
Cleanup: c.Bool("cleanup"),
ContextSubPath: c.String("context-sub-path"),
CustomPlatform: c.String("custom-platform"),
Force: c.Bool("force"),
ImageNameWithDigestFile: c.String("image-name-with-digest-file"),
ImageNameTagWithDigestFile: c.String("image-name-tag-with-digest-file"),
Insecure: c.Bool("insecure"),
InsecurePull: c.Bool("insecure-pull"),
InsecureRegistry: c.String("insecure-registry"),
Label: c.String("label"),
LogFormat: c.String("log-format"),
LogTimestamp: c.Bool("log-timestamp"),
OCILayoutPath: c.String("oci-layout-path"),
PushRetry: c.Int("push-retry"),
RegistryCertificate: c.String("registry-certificate"),
RegistryClientCert: c.String("registry-client-cert"),
SkipDefaultRegistryFallback: c.Bool("skip-default-registry-fallback"),
Reproducible: c.Bool("reproducible"),
SingleSnapshot: c.Bool("single-snapshot"),
SkipTLSVerify: c.Bool("skip-tls-verify"),
SkipPushPermissionCheck: c.Bool("skip-push-permission-check"),
SkipTLSVerifyPull: c.Bool("skip-tls-verify-pull"),
SkipTLSVerifyRegistry: c.Bool("skip-tls-verify-registry"),
UseNewRun: c.Bool("use-new-run"),
IgnorePath: c.String("ignore-path"),
IgnorePaths: c.StringSlice("ignore-paths"),
ImageFSExtractRetry: c.Int("image-fs-extract-retry"),
ImageDownloadRetry: c.Int("image-download-retry"),
},
Artifact: kaniko.Artifact{
Tags: c.StringSlice("tags"),
@@ -264,11 +463,19 @@ func run(c *cli.Context) error {
RegistryType: artifact.Docker,
},
}
if c.IsSet("compressed-caching") {
flag := c.Bool("compressed-caching")
plugin.Build.CompressedCaching = &flag
}
if c.IsSet("ignore-var-run") {
flag := c.Bool("ignore-var-run")
plugin.Build.IgnoreVarRun = &flag
}
return plugin.Exec()
}
func setupAuth(tenantId, clientId, cert,
clientSecret, subscriptionId, registry string, noPush bool) (string, error) {
clientSecret, subscriptionId, registry, dockerUsername, dockerPassword, dockerRegistry string, noPush bool) (string, error) {
if registry == "" {
return "", fmt.Errorf("registry must be specified")
}
@@ -285,8 +492,9 @@ func setupAuth(tenantId, clientId, cert,
if err != nil {
return "", errors.Wrap(err, "failed to fetch ACR Token")
}
err = docker.CreateDockerCfgFile(username, token, registry, dockerConfigPath)
if err != nil {
// setup docker config for azure registry and base image docker registry
if err := setDockerAuth(username, token, registry, dockerUsername, dockerPassword, dockerRegistry); err != nil {
return "", errors.Wrap(err, "failed to create docker config")
}
return publicUrl, nil
@@ -460,6 +668,25 @@ func getPublicUrl(token, registryUrl, subscriptionId string) (string, error) {
return "", errors.New("did not receive any registry information from /subscriptions API")
}
func setDockerAuth(username, password, registry, dockerUsername, dockerPassword, dockerRegistry string) error {
dockerConfig := docker.NewConfig()
pushToRegistryCreds := docker.RegistryCredentials{
Registry: registry,
Username: username,
Password: password,
}
pullFromRegistryCreds := docker.RegistryCredentials{
Registry: dockerRegistry,
Username: dockerUsername,
Password: dockerPassword,
}
credentials := []docker.RegistryCredentials{pushToRegistryCreds, pullFromRegistryCreds}
return dockerConfig.CreateDockerConfig(credentials, dockerConfigPath)
}
func encodeParam(s string) string {
return url.QueryEscape(s)
}
+156
View File
@@ -0,0 +1,156 @@
package main
import (
"encoding/base64"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/drone/drone-kaniko/pkg/docker"
"github.com/stretchr/testify/assert"
)
const (
v2RegistryURL string = "https://index.docker.io/v2/" // v2 registry is not supported
)
func TestCreateDockerConfigWithBaseRegistry(t *testing.T) {
username := "user1"
password := "pass1"
registry := "azurecr.io"
dockerUsername := "dockeruser"
dockerPassword := "dockerpass"
dockerRegistry := "https://index.docker.io/v1/"
privateRegistry := "privateDockerRegistry"
privateRegistryUsername := "priaveUsername"
privateRegistryPassword := "privatePassword"
credentials := []docker.RegistryCredentials{
{
Registry: registry,
Username: username,
Password: password,
},
{
Registry: dockerRegistry,
Username: dockerUsername,
Password: dockerPassword,
},
{
Registry: privateRegistry,
Username: privateRegistryUsername,
Password: privateRegistryPassword,
},
}
tempDir, err := ioutil.TempDir("", "docker-config-test")
assert.NoError(t, err)
defer os.RemoveAll(tempDir)
config := docker.NewConfig()
err = config.CreateDockerConfig(credentials, tempDir)
assert.NoError(t, err)
expectedAuth := docker.Auth{Auth: base64.StdEncoding.EncodeToString([]byte(username + ":" + password))}
assert.Equal(t, expectedAuth, config.Auths[registry])
expectedDockerAuth := docker.Auth{Auth: base64.StdEncoding.EncodeToString([]byte(dockerUsername + ":" + dockerPassword))}
assert.Equal(t, expectedDockerAuth, config.Auths[dockerRegistry])
configPath := filepath.Join(tempDir, "config.json")
data, err := ioutil.ReadFile(configPath)
assert.NoError(t, err)
var configFromFile docker.Config
err = json.Unmarshal(data, &configFromFile)
assert.NoError(t, err)
assert.Equal(t, config.Auths, configFromFile.Auths)
err = config.CreateDockerConfig([]docker.RegistryCredentials{
{
Registry: registry,
Username: "",
Password: password,
},
}, tempDir)
assert.EqualError(t, err, "Username must be specified for registry: "+registry)
err = config.CreateDockerConfig([]docker.RegistryCredentials{
{
Registry: registry,
Username: username,
Password: "",
},
}, tempDir)
assert.EqualError(t, err, "Password must be specified for registry: "+registry)
// v1 registry but without username password
err = config.CreateDockerConfig([]docker.RegistryCredentials{
{
Registry: registry,
Username: username,
Password: password,
},
{
Registry: dockerRegistry,
Username: "",
Password: "",
},
}, tempDir)
assert.EqualError(t, err, "Username must be specified for registry: "+dockerRegistry)
// private base registry without username/password
err = config.CreateDockerConfig([]docker.RegistryCredentials{
{
Registry: privateRegistry,
Username: "",
Password: "",
},
}, tempDir)
assert.EqualError(t, err, "Username must be specified for registry: "+privateRegistry)
}
func TestCreateDockerConfigWithoutBaseRegistry(t *testing.T) {
username := "user1"
password := "pass1"
registry := "azurecr.io"
credentials := []docker.RegistryCredentials{
{
Registry: registry,
Username: username,
Password: password,
},
}
// Create a temporary directory
tempDir, err := ioutil.TempDir("", "docker-config-test")
assert.NoError(t, err)
defer os.RemoveAll(tempDir)
config := docker.NewConfig()
err = config.CreateDockerConfig(credentials, tempDir)
assert.NoError(t, err)
expectedAuth := docker.Auth{Auth: base64.StdEncoding.EncodeToString([]byte(username + ":" + password))}
assert.Equal(t, expectedAuth, config.Auths[registry])
// Check the contents of the config.json file
configPath := filepath.Join(tempDir, "config.json")
data, err := ioutil.ReadFile(configPath)
assert.NoError(t, err)
var configFromFile docker.Config
err = json.Unmarshal(data, &configFromFile)
assert.NoError(t, err)
assert.Equal(t, config.Auths, configFromFile.Auths)
// Check if the public Docker Hub auth is not set
_, exists := config.Auths[""]
assert.False(t, exists)
}
+282 -76
View File
@@ -1,9 +1,6 @@
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"strings"
@@ -14,6 +11,7 @@ import (
kaniko "github.com/drone/drone-kaniko"
"github.com/drone/drone-kaniko/pkg/artifact"
"github.com/drone/drone-kaniko/pkg/docker"
)
const (
@@ -21,9 +19,7 @@ const (
dockerPath string = "/kaniko/.docker"
dockerConfigPath string = "/kaniko/.docker/config.json"
v1RegistryURL string = "https://index.docker.io/v1/" // Default registry
v2RegistryURL string = "https://index.docker.io/v2/" // v2 registry is not supported
v2HubRegistryURL string = "https://registry.hub.docker.com/v2/"
v1RegistryURL string = "https://index.docker.io/v1/" // Default registry
defaultDigestFile string = "/kaniko/digest-file"
)
@@ -122,10 +118,15 @@ func main() {
},
cli.StringFlag{
Name: "registry",
Usage: "docker registry",
Usage: "docker registry of registry to push image to",
Value: v1RegistryURL,
EnvVar: "PLUGIN_REGISTRY",
},
cli.StringFlag{
Name: "base-image-registry",
Usage: "Docker registry for base image",
EnvVar: "PLUGIN_DOCKER_REGISTRY,PLUGIN_BASE_IMAGE_REGISTRY,DOCKER_REGISTRY",
},
cli.StringSliceFlag{
Name: "registry-mirrors",
Usage: "docker registry mirrors",
@@ -133,14 +134,24 @@ func main() {
},
cli.StringFlag{
Name: "username",
Usage: "docker username",
Usage: "docker username of registry to push image to",
EnvVar: "PLUGIN_USERNAME",
},
cli.StringFlag{
Name: "base-image-username",
Usage: "Docker username for base image registry",
EnvVar: "PLUGIN_DOCKER_USERNAME,PLUGIN_BASE_IMAGE_USERNAME,DOCKER_USERNAME",
},
cli.StringFlag{
Name: "password",
Usage: "docker password",
Usage: "docker password of registry to push image to",
EnvVar: "PLUGIN_PASSWORD",
},
cli.StringFlag{
Name: "base-image-password",
Usage: "Docker password for base image registry",
EnvVar: "PLUGIN_DOCKER_PASSWORD,PLUGIN_BASE_IMAGE_PASSWORD,DOCKER_PASSWORD",
},
cli.BoolFlag{
Name: "skip-tls-verify",
Usage: "Skip registry tls verify",
@@ -179,7 +190,7 @@ func main() {
cli.StringFlag{
Name: "tar-path",
Usage: "Set this flag to save the image as a tarball at path",
EnvVar: "PLUGIN_TAR_PATH",
EnvVar: "PLUGIN_TAR_PATH, PLUGIN_DESTINATION_TAR_PATH",
},
cli.StringFlag{
Name: "verbosity",
@@ -201,6 +212,172 @@ func main() {
Usage: "Output file location that will be generated by the plugin. This file will include information of the output that are exported by the plugin.",
EnvVar: "DRONE_OUTPUT",
},
cli.StringFlag{
Name: "cache-dir",
Usage: "Set this flag to specify a local directory cache for base images",
EnvVar: "PLUGIN_CACHE_DIR",
},
cli.BoolFlag{
Name: "cache-copy-layers",
Usage: "Enable or disable copying layers from the cache.",
EnvVar: "PLUGIN_CACHE_COPY_LAYERS",
},
cli.BoolFlag{
Name: "cache-run-layers",
Usage: "Enable or disable running layers from the cache.",
EnvVar: "PLUGIN_CACHE_RUN_LAYERS",
},
cli.BoolFlag{
Name: "cleanup",
Usage: "Enable or disable cleanup of temporary files.",
EnvVar: "PLUGIN_CLEANUP",
},
cli.BoolFlag{
Name: "compressed-caching",
Usage: "Enable or disable compressed caching.",
EnvVar: "PLUGIN_COMPRESSED_CACHING",
},
cli.StringFlag{
Name: "context-sub-path",
Usage: "Sub-path within the context to build.",
EnvVar: "PLUGIN_CONTEXT_SUB_PATH",
},
cli.StringFlag{
Name: "custom-platform",
Usage: "Platform to use for building.",
EnvVar: "PLUGIN_CUSTOM_PLATFORM",
},
cli.BoolFlag{
Name: "force",
Usage: "Force building the image even if it already exists.",
EnvVar: "PLUGIN_FORCE",
},
cli.StringFlag{
Name: "image-name-with-digest-file",
Usage: "Write image name with digest to a file.",
EnvVar: "PLUGIN_IMAGE_NAME_WITH_DIGEST_FILE",
},
cli.StringFlag{
Name: "image-name-tag-with-digest-file",
Usage: "Write image name with tag and digest to a file.",
EnvVar: "PLUGIN_IMAGE_NAME_TAG_WITH_DIGEST_FILE",
},
cli.BoolFlag{
Name: "insecure",
Usage: "Allow connecting to registries without TLS.",
EnvVar: "PLUGIN_INSECURE",
},
cli.BoolFlag{
Name: "insecure-pull",
Usage: "Allow insecure pulls from the registry.",
EnvVar: "PLUGIN_INSECURE_PULL",
},
cli.StringFlag{
Name: "insecure-registry",
Usage: "Use plain HTTP for registry communication.",
EnvVar: "PLUGIN_INSECURE_REGISTRY",
},
cli.StringFlag{
Name: "log-format",
Usage: "Set the log format for build output.",
EnvVar: "PLUGIN_LOG_FORMAT",
},
cli.BoolFlag{
Name: "log-timestamp",
Usage: "Show timestamps in build output.",
EnvVar: "PLUGIN_LOG_TIMESTAMP",
},
cli.StringFlag{
Name: "oci-layout-path",
Usage: "Directory to store OCI layout.",
EnvVar: "PLUGIN_OCI_LAYOUT_PATH",
},
cli.IntFlag{
Name: "push-retry",
Usage: "Number of times to retry pushing an image.",
EnvVar: "PLUGIN_PUSH_RETRY",
},
cli.StringFlag{
Name: "registry-certificate",
Usage: "Path to a file containing a registry certificate.",
EnvVar: "PLUGIN_REGISTRY_CERTIFICATE",
},
cli.StringFlag{
Name: "registry-client-cert",
Usage: "Path to a file containing a registry client certificate.",
EnvVar: "PLUGIN_REGISTRY_CLIENT_CERT",
},
cli.BoolFlag{
Name: "skip-default-registry-fallback",
Usage: "Skip Docker Hub and default registry fallback.",
EnvVar: "PLUGIN_SKIP_DEFAULT_REGISTRY_FALLBACK",
},
cli.BoolFlag{
Name: "reproducible",
Usage: "Create a reproducible image.",
EnvVar: "PLUGIN_REPRODUCIBLE",
},
cli.BoolFlag{
Name: "single-snapshot",
Usage: "Only create a single snapshot of the image.",
EnvVar: "PLUGIN_SINGLE_SNAPSHOT",
},
cli.BoolFlag{
Name: "skip-push-permission-check",
Usage: "Skip permission check when pushing.",
EnvVar: "PLUGIN_SKIP_PUSH_PERMISSION_CHECK",
},
cli.BoolFlag{
Name: "skip-tls-verify-pull",
Usage: "Skip TLS verification when pulling.",
EnvVar: "PLUGIN_SKIP_TLS_VERIFY_PULL",
},
cli.BoolFlag{
Name: "skip-tls-verify-registry",
Usage: "Skip TLS verification when connecting to a registry.",
EnvVar: "PLUGIN_SKIP_TLS_VERIFY_REGISTRY",
},
cli.BoolFlag{
Name: "use-new-run",
Usage: "Skip TLS verification when connecting to a registry.",
EnvVar: "PLUGIN_USE_NEW_RUN",
},
cli.BoolFlag{
Name: "ignore-var-run",
Usage: "Ignore the /var/run directory during build.",
EnvVar: "PLUGIN_IGNORE_VAR_RUN",
},
cli.StringFlag{
Name: "ignore-path",
Usage: "Path to ignore during the build.",
EnvVar: "PLUGIN_IGNORE_PATH",
},
cli.StringSliceFlag{
Name: "ignore-paths",
Usage: "Path to ignore during the build.",
EnvVar: "PLUGIN_IGNORE_PATHS",
},
cli.IntFlag{
Name: "image-fs-extract-retry",
Usage: "Number of retries for extracting filesystem layers.",
EnvVar: "PLUGIN_IMAGE_FS_EXTRACT_RETRY",
},
cli.IntFlag{
Name: "image-download-retry",
Usage: "Number of retries for downloading base images.",
EnvVar: "PLUGIN_IMAGE_DOWNLOAD_RETRY",
},
cli.StringFlag{
Name: "source-tar-path",
Usage: "Set this flag for the source tarball during push operations.",
EnvVar: "PLUGIN_SOURCE_TAR_PATH",
},
cli.BoolFlag{
Name: "push-only",
Usage: "Specify if the operation is push-only",
EnvVar: "PLUGIN_PUSH_ONLY",
},
}
if err := app.Run(os.Args); err != nil {
@@ -212,45 +389,86 @@ func run(c *cli.Context) error {
username := c.String("username")
noPush := c.Bool("no-push")
configOverride := c.String("dockerconfig")
// if configOverride is provided, use this for docker auth
// if configOverride is provided, use this directly to write to docker config file
if len(configOverride) > 0 {
if err := writeDockerCfgFile([]byte(configOverride)); err != nil {
if err := docker.WriteDockerConfig([]byte(configOverride), dockerPath); err != nil {
return err
}
} else if !noPush || username != "" {
// setup auth when pushing or credentials are defined and docker config override is false
if err := createDockerCfgFile(username, c.String("password"), c.String("registry")); err != nil {
return err
// setup auth when pushing/pulling or credentials are defined and docker config override is false
err := setDockerAuth(
c.String("username"),
c.String("password"),
c.String("registry"),
c.String("base-image-username"),
c.String("base-image-password"),
c.String("base-image-registry"),
)
if err != nil {
return errors.Wrap(err, "failed to create docker config")
}
}
plugin := kaniko.Plugin{
Build: kaniko.Build{
DroneCommitRef: c.String("drone-commit-ref"),
DroneRepoBranch: c.String("drone-repo-branch"),
Dockerfile: c.String("dockerfile"),
Context: c.String("context"),
Tags: c.StringSlice("tags"),
AutoTag: c.Bool("auto-tag"),
AutoTagSuffix: c.String("auto-tag-suffix"),
ExpandTag: c.Bool("expand-tag"),
Args: c.StringSlice("args"),
Target: c.String("target"),
Repo: buildRepo(c.String("registry"), c.String("repo"), c.Bool("expand-repo")),
Mirrors: c.StringSlice("registry-mirrors"),
Labels: c.StringSlice("custom-labels"),
SkipTlsVerify: c.Bool("skip-tls-verify"),
SnapshotMode: c.String("snapshot-mode"),
EnableCache: c.Bool("enable-cache"),
CacheRepo: buildRepo(c.String("registry"), c.String("cache-repo"), c.Bool("expand-repo")),
CacheTTL: c.Int("cache-ttl"),
DigestFile: defaultDigestFile,
NoPush: noPush,
TarPath: c.String("tar-path"),
Verbosity: c.String("verbosity"),
Platform: c.String("platform"),
SkipUnusedStages: c.Bool("skip-unused-stages"),
DroneCommitRef: c.String("drone-commit-ref"),
DroneRepoBranch: c.String("drone-repo-branch"),
Dockerfile: c.String("dockerfile"),
Context: c.String("context"),
Tags: c.StringSlice("tags"),
AutoTag: c.Bool("auto-tag"),
AutoTagSuffix: c.String("auto-tag-suffix"),
ExpandTag: c.Bool("expand-tag"),
Args: c.StringSlice("args"),
Target: c.String("target"),
Repo: buildRepo(c.String("registry"), c.String("repo"), c.Bool("expand-repo")),
Mirrors: c.StringSlice("registry-mirrors"),
Labels: c.StringSlice("custom-labels"),
SkipTlsVerify: c.Bool("skip-tls-verify"),
SnapshotMode: c.String("snapshot-mode"),
EnableCache: c.Bool("enable-cache"),
CacheRepo: buildRepo(c.String("registry"), c.String("cache-repo"), c.Bool("expand-repo")),
CacheTTL: c.Int("cache-ttl"),
DigestFile: defaultDigestFile,
NoPush: noPush,
TarPath: c.String("tar-path"),
Verbosity: c.String("verbosity"),
Platform: c.String("platform"),
PushOnly: c.Bool("push-only"),
SkipUnusedStages: c.Bool("skip-unused-stages"),
CacheDir: c.String("cache-dir"),
CacheCopyLayers: c.Bool("cache-copy-layers"),
CacheRunLayers: c.Bool("cache-run-layers"),
Cleanup: c.Bool("cleanup"),
ContextSubPath: c.String("context-sub-path"),
CustomPlatform: c.String("custom-platform"),
Force: c.Bool("force"),
ImageNameWithDigestFile: c.String("image-name-with-digest-file"),
ImageNameTagWithDigestFile: c.String("image-name-tag-with-digest-file"),
Insecure: c.Bool("insecure"),
InsecurePull: c.Bool("insecure-pull"),
InsecureRegistry: c.String("insecure-registry"),
Label: c.String("label"),
LogFormat: c.String("log-format"),
LogTimestamp: c.Bool("log-timestamp"),
OCILayoutPath: c.String("oci-layout-path"),
PushRetry: c.Int("push-retry"),
RegistryCertificate: c.String("registry-certificate"),
RegistryClientCert: c.String("registry-client-cert"),
SkipDefaultRegistryFallback: c.Bool("skip-default-registry-fallback"),
Reproducible: c.Bool("reproducible"),
SingleSnapshot: c.Bool("single-snapshot"),
SkipTLSVerify: c.Bool("skip-tls-verify"),
SkipPushPermissionCheck: c.Bool("skip-push-permission-check"),
SkipTLSVerifyPull: c.Bool("skip-tls-verify-pull"),
SkipTLSVerifyRegistry: c.Bool("skip-tls-verify-registry"),
SourceTarPath: c.String("source-tar-path"),
UseNewRun: c.Bool("use-new-run"),
IgnorePath: c.String("ignore-path"),
IgnorePaths: c.StringSlice("ignore-paths"),
ImageFSExtractRetry: c.Int("image-fs-extract-retry"),
ImageDownloadRetry: c.Int("image-download-retry"),
},
Artifact: kaniko.Artifact{
Tags: c.StringSlice("tags"),
@@ -263,48 +481,36 @@ func run(c *cli.Context) error {
OutputFile: c.String("output-file"),
},
}
if c.IsSet("compressed-caching") {
flag := c.Bool("compressed-caching")
plugin.Build.CompressedCaching = &flag
}
if c.IsSet("ignore-var-run") {
flag := c.Bool("ignore-var-run")
plugin.Build.IgnoreVarRun = &flag
}
return plugin.Exec()
}
// Create the docker config file for authentication
func createDockerCfgFile(username, password, registry string) error {
if username == "" {
return fmt.Errorf("Username must be specified")
}
if password == "" {
return fmt.Errorf("Password must be specified")
}
if registry == "" {
return fmt.Errorf("Registry must be specified")
func setDockerAuth(username, password, registry, baseImageUsername, baseImagePassword, baseImageRegistry string) error {
dockerConfig := docker.NewConfig()
pushToRegistryCreds := docker.RegistryCredentials{
Registry: registry,
Username: username,
Password: password,
}
credentials := []docker.RegistryCredentials{pushToRegistryCreds}
if registry == v2RegistryURL || registry == v2HubRegistryURL {
fmt.Println("Docker v2 registry is not supported in kaniko. Refer issue: https://github.com/GoogleContainerTools/kaniko/issues/1209")
fmt.Printf("Using v1 registry instead: %s\n", v1RegistryURL)
registry = v1RegistryURL
if baseImageRegistry != "" {
pullFromRegistryCreds := docker.RegistryCredentials{
Registry: baseImageRegistry,
Username: baseImageUsername,
Password: baseImagePassword,
}
credentials = append(credentials, pullFromRegistryCreds)
}
authBytes := []byte(fmt.Sprintf("%s:%s", username, password))
encodedString := base64.StdEncoding.EncodeToString(authBytes)
jsonBytes := []byte(fmt.Sprintf(`{"auths": {"%s": {"auth": "%s"}}}`, registry, encodedString))
if err := writeDockerCfgFile(jsonBytes); err != nil {
return errors.Wrap(err, "failed to write docker config file")
}
return nil
}
// Write json bytes in the docker config file
func writeDockerCfgFile(jsonBytes []byte) error {
err := os.MkdirAll(dockerPath, 0600)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to create %s directory", dockerPath))
}
err = ioutil.WriteFile(dockerConfigPath, jsonBytes, 0644)
if err != nil {
return errors.Wrap(err, "failed to create docker config file")
}
return nil
// Creates docker config for both the regustries used for authentication
return dockerConfig.CreateDockerConfig(credentials, dockerPath)
}
func buildRepo(registry, repo string, expandRepo bool) string {
+87 -1
View File
@@ -1,6 +1,12 @@
package main
import "testing"
import (
"io/ioutil"
"os"
"testing"
"github.com/drone/drone-kaniko/pkg/docker"
)
func Test_buildRepo(t *testing.T) {
tests := []struct {
@@ -35,3 +41,83 @@ func Test_buildRepo(t *testing.T) {
})
}
}
func TestCreateDockerConfig(t *testing.T) {
config := docker.NewConfig()
tempDir, err := ioutil.TempDir("", "docker-config-test")
if err != nil {
t.Fatalf("Failed to create temporary directory: %v", err)
}
defer os.RemoveAll(tempDir)
tests := []struct {
name string
credentials []docker.RegistryCredentials
wantErr bool
}{
{
name: "valid credentials",
credentials: []docker.RegistryCredentials{
{
Registry: "https://index.docker.io/v1/",
Username: "testuser",
Password: "testpassword",
},
},
wantErr: false,
},
{
name: "v2 registry",
credentials: []docker.RegistryCredentials{
{
Registry: "https://index.docker.io/v2/",
Username: "testuser",
Password: "testpassword",
},
},
wantErr: false,
},
{
name: "docker registry credentials",
credentials: []docker.RegistryCredentials{
{
Registry: "https://index.docker.io/v1/",
Username: "testuser",
Password: "testpassword",
},
{
Registry: "https://docker.io",
Username: "dockeruser",
Password: "dockerpassword",
},
},
wantErr: false,
},
{
name: "empty docker registry",
credentials: []docker.RegistryCredentials{
{
Registry: "https://index.docker.io/v1/",
Username: "testuser",
Password: "testpassword",
},
{
Registry: "https://docker.io",
Username: "dockeruser",
Password: "",
},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := config.CreateDockerConfig(tt.credentials, tempDir)
if (err != nil) != tt.wantErr {
t.Errorf("CreateDockerConfig() error = %v, wantErr %v", err, tt.wantErr)
return
}
})
}
}
+33
View File
@@ -0,0 +1,33 @@
package main
import (
"strings"
)
// CustomStringSliceFlag is like a regular StringSlice flag but with
// semicolon as a delimiter
type CustomStringSliceFlag struct {
Value []string
}
func (f *CustomStringSliceFlag) GetValue() []string {
if f.Value == nil {
return make([]string, 0)
}
return f.Value
}
func (f *CustomStringSliceFlag) String() string {
if f.Value == nil {
return ""
}
return strings.Join(f.Value, ";")
}
func (f *CustomStringSliceFlag) Set(v string) error {
for _, s := range strings.Split(v, ";") {
s = strings.TrimSpace(s)
f.Value = append(f.Value, s)
}
return nil
}
+319 -57
View File
@@ -3,11 +3,11 @@ package main
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
@@ -18,6 +18,7 @@ import (
"github.com/aws/aws-sdk-go/aws/session"
ecrv1 "github.com/aws/aws-sdk-go/service/ecr"
ecrpublicv1 "github.com/aws/aws-sdk-go/service/ecrpublic"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/aws/smithy-go"
"github.com/hashicorp/go-version"
"github.com/joho/godotenv"
@@ -32,10 +33,11 @@ import (
const (
accessKeyEnv string = "AWS_ACCESS_KEY_ID"
dockerConfigPath string = "/kaniko/.docker"
secretKeyEnv string = "AWS_SECRET_ACCESS_KEY"
dockerConfigPath string = "/kaniko/.docker/config.json"
ecrPublicDomain string = "public.ecr.aws"
kanikoVersionEnv string = "KANIKO_VERSION"
sessionKeyEnv string = "AWS_SESSION_TOKEN"
oneDotEightVersion string = "1.8.0"
defaultDigestFile string = "/kaniko/digest-file"
@@ -67,18 +69,18 @@ func main() {
},
cli.StringFlag{
Name: "docker-registry",
Usage: "docker registry",
EnvVar: "PLUGIN_DOCKER_REGISTRY,DOCKER_REGISTRY",
Usage: "Docker registry for base image",
EnvVar: "PLUGIN_DOCKER_REGISTRY,DOCKER_REGISTRY,PLUGIN_BASE_IMAGE_REGISTRY",
},
cli.StringFlag{
Name: "docker-username",
Usage: "docker username",
EnvVar: "PLUGIN_USERNAME,DOCKER_USERNAME",
Usage: "Docker username for base image registry",
EnvVar: "PLUGIN_USERNAME,PLUGIN_DOCKER_USERNAME,PLUGIN_BASE_IMAGE_USERNAME,DOCKER_USERNAME",
},
cli.StringFlag{
Name: "docker-password",
Usage: "docker password",
EnvVar: "PLUGIN_PASSWORD,DOCKER_PASSWORD",
Usage: "Docker password for base image registry",
EnvVar: "PLUGIN_PASSWORD,PLUGIN_DOCKER_PASSWORD,PLUGIN_BASE_IMAGE_PASSWORD,DOCKER_PASSWORD",
},
cli.StringFlag{
Name: "context",
@@ -123,6 +125,17 @@ func main() {
Usage: "build args",
EnvVar: "PLUGIN_BUILD_ARGS",
},
cli.GenericFlag{
Name: "args-new",
Usage: "build args new",
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
Value: new(CustomStringSliceFlag),
},
cli.BoolFlag{
Name: "plugin-multiple-build-agrs",
Usage: "plugin multiple build agrs",
EnvVar: "PLUGIN_MULTIPLE_BUILD_ARGS",
},
cli.StringFlag{
Name: "target",
Usage: "build target",
@@ -234,6 +247,162 @@ func main() {
Usage: "build only used stages",
EnvVar: "PLUGIN_SKIP_UNUSED_STAGES",
},
cli.StringFlag{
Name: "cache-dir",
Usage: "Set this flag to specify a local directory cache for base images",
EnvVar: "PLUGIN_CACHE_DIR",
},
cli.BoolFlag{
Name: "cache-copy-layers",
Usage: "Enable or disable copying layers from the cache.",
EnvVar: "PLUGIN_CACHE_COPY_LAYERS",
},
cli.BoolFlag{
Name: "cache-run-layers",
Usage: "Enable or disable running layers from the cache.",
EnvVar: "PLUGIN_CACHE_RUN_LAYERS",
},
cli.BoolFlag{
Name: "cleanup",
Usage: "Enable or disable cleanup of temporary files.",
EnvVar: "PLUGIN_CLEANUP",
},
cli.BoolFlag{
Name: "compressed-caching",
Usage: "Enable or disable compressed caching.",
EnvVar: "PLUGIN_COMPRESSED_CACHING",
},
cli.StringFlag{
Name: "context-sub-path",
Usage: "Sub-path within the context to build.",
EnvVar: "PLUGIN_CONTEXT_SUB_PATH",
},
cli.StringFlag{
Name: "custom-platform",
Usage: "Platform to use for building.",
EnvVar: "PLUGIN_CUSTOM_PLATFORM",
},
cli.BoolFlag{
Name: "force",
Usage: "Force building the image even if it already exists.",
EnvVar: "PLUGIN_FORCE",
},
cli.StringFlag{
Name: "image-name-with-digest-file",
Usage: "Write image name with digest to a file.",
EnvVar: "PLUGIN_IMAGE_NAME_WITH_DIGEST_FILE",
},
cli.StringFlag{
Name: "image-name-tag-with-digest-file",
Usage: "Write image name with tag and digest to a file.",
EnvVar: "PLUGIN_IMAGE_NAME_TAG_WITH_DIGEST_FILE",
},
cli.BoolFlag{
Name: "insecure",
Usage: "Allow connecting to registries without TLS.",
EnvVar: "PLUGIN_INSECURE",
},
cli.BoolFlag{
Name: "insecure-pull",
Usage: "Allow insecure pulls from the registry.",
EnvVar: "PLUGIN_INSECURE_PULL",
},
cli.StringFlag{
Name: "insecure-registry",
Usage: "Use plain HTTP for registry communication.",
EnvVar: "PLUGIN_INSECURE_REGISTRY",
},
cli.StringFlag{
Name: "log-format",
Usage: "Set the log format for build output.",
EnvVar: "PLUGIN_LOG_FORMAT",
},
cli.BoolFlag{
Name: "log-timestamp",
Usage: "Show timestamps in build output.",
EnvVar: "PLUGIN_LOG_TIMESTAMP",
},
cli.StringFlag{
Name: "oci-layout-path",
Usage: "Directory to store OCI layout.",
EnvVar: "PLUGIN_OCI_LAYOUT_PATH",
},
cli.IntFlag{
Name: "push-retry",
Usage: "Number of times to retry pushing an image.",
EnvVar: "PLUGIN_PUSH_RETRY",
},
cli.StringFlag{
Name: "registry-certificate",
Usage: "Path to a file containing a registry certificate.",
EnvVar: "PLUGIN_REGISTRY_CERTIFICATE",
},
cli.StringFlag{
Name: "registry-client-cert",
Usage: "Path to a file containing a registry client certificate.",
EnvVar: "PLUGIN_REGISTRY_CLIENT_CERT",
},
cli.BoolFlag{
Name: "skip-default-registry-fallback",
Usage: "Skip Docker Hub and default registry fallback.",
EnvVar: "PLUGIN_SKIP_DEFAULT_REGISTRY_FALLBACK",
},
cli.BoolFlag{
Name: "reproducible",
Usage: "Create a reproducible image.",
EnvVar: "PLUGIN_REPRODUCIBLE",
},
cli.BoolFlag{
Name: "single-snapshot",
Usage: "Only create a single snapshot of the image.",
EnvVar: "PLUGIN_SINGLE_SNAPSHOT",
},
cli.BoolFlag{
Name: "skip-push-permission-check",
Usage: "Skip permission check when pushing.",
EnvVar: "PLUGIN_SKIP_PUSH_PERMISSION_CHECK",
},
cli.BoolFlag{
Name: "skip-tls-verify-pull",
Usage: "Skip TLS verification when pulling.",
EnvVar: "PLUGIN_SKIP_TLS_VERIFY_PULL",
},
cli.BoolFlag{
Name: "skip-tls-verify-registry",
Usage: "Skip TLS verification when connecting to a registry.",
EnvVar: "PLUGIN_SKIP_TLS_VERIFY_REGISTRY",
},
cli.BoolFlag{
Name: "use-new-run",
Usage: "Skip TLS verification when connecting to a registry.",
EnvVar: "PLUGIN_USE_NEW_RUN",
},
cli.BoolFlag{
Name: "ignore-var-run",
Usage: "Ignore the /var/run directory during build.",
EnvVar: "PLUGIN_IGNORE_VAR_RUN",
},
cli.StringFlag{
Name: "ignore-path",
Usage: "Path to ignore during the build.",
EnvVar: "PLUGIN_IGNORE_PATH",
},
cli.IntFlag{
Name: "image-fs-extract-retry",
Usage: "Number of retries for extracting filesystem layers.",
EnvVar: "PLUGIN_IMAGE_FS_EXTRACT_RETRY",
},
cli.IntFlag{
Name: "image-download-retry",
Usage: "Number of retries for downloading base images.",
EnvVar: "PLUGIN_IMAGE_DOWNLOAD_RETRY",
},
cli.StringFlag{
Name: "oidc-token-id",
Usage: "OIDC token for assuming role via web identity",
EnvVar: "PLUGIN_OIDC_TOKEN_ID",
},
}
if err := app.Run(os.Args); err != nil {
@@ -248,8 +417,10 @@ func run(c *cli.Context) error {
noPush := c.Bool("no-push")
assumeRole := c.String("assume-role")
externalId := c.String("external-id")
oidcToken := c.String("oidc-token-id")
dockerConfig, err := createDockerConfig(
// setup docker config for azure registry and base image docker registry
err := setDockerAuth(
c.String("docker-registry"),
c.String("docker-username"),
c.String("docker-password"),
@@ -260,18 +431,10 @@ func run(c *cli.Context) error {
externalId,
region,
noPush,
oidcToken,
)
if err != nil {
return err
}
jsonBytes, err := json.Marshal(dockerConfig)
if err != nil {
return err
}
if err := ioutil.WriteFile(dockerConfigPath, jsonBytes, 0644); err != nil {
return err
return errors.Wrap(err, "failed to create docker config")
}
// only create repository when pushing and create-repository is true
@@ -303,28 +466,61 @@ func run(c *cli.Context) error {
plugin := kaniko.Plugin{
Build: kaniko.Build{
DroneCommitRef: c.String("drone-commit-ref"),
DroneRepoBranch: c.String("drone-repo-branch"),
Dockerfile: c.String("dockerfile"),
Context: c.String("context"),
Tags: c.StringSlice("tags"),
AutoTag: c.Bool("auto-tag"),
AutoTagSuffix: c.String("auto-tag-suffix"),
ExpandTag: c.Bool("expand-tag"),
Args: c.StringSlice("args"),
Target: c.String("target"),
Repo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("repo")),
Mirrors: c.StringSlice("registry-mirrors"),
Labels: c.StringSlice("custom-labels"),
SnapshotMode: c.String("snapshot-mode"),
EnableCache: c.Bool("enable-cache"),
CacheRepo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("cache-repo")),
CacheTTL: c.Int("cache-ttl"),
DigestFile: defaultDigestFile,
NoPush: noPush,
Verbosity: c.String("verbosity"),
Platform: c.String("platform"),
SkipUnusedStages: c.Bool("skip-unused-stages"),
DroneCommitRef: c.String("drone-commit-ref"),
DroneRepoBranch: c.String("drone-repo-branch"),
Dockerfile: c.String("dockerfile"),
Context: c.String("context"),
Tags: c.StringSlice("tags"),
AutoTag: c.Bool("auto-tag"),
AutoTagSuffix: c.String("auto-tag-suffix"),
ExpandTag: c.Bool("expand-tag"),
Args: c.StringSlice("args"),
ArgsNew: c.Generic("args-new").(*CustomStringSliceFlag).GetValue(),
IsMultipleBuildArgs: c.Bool("plugin-multiple-build-agrs"),
Target: c.String("target"),
Repo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("repo")),
Mirrors: c.StringSlice("registry-mirrors"),
Labels: c.StringSlice("custom-labels"),
SnapshotMode: c.String("snapshot-mode"),
EnableCache: c.Bool("enable-cache"),
CacheRepo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("cache-repo")),
CacheTTL: c.Int("cache-ttl"),
DigestFile: defaultDigestFile,
NoPush: noPush,
Verbosity: c.String("verbosity"),
Platform: c.String("platform"),
SkipUnusedStages: c.Bool("skip-unused-stages"),
CacheDir: c.String("cache-dir"),
CacheCopyLayers: c.Bool("cache-copy-layers"),
CacheRunLayers: c.Bool("cache-run-layers"),
Cleanup: c.Bool("cleanup"),
ContextSubPath: c.String("context-sub-path"),
CustomPlatform: c.String("custom-platform"),
Force: c.Bool("force"),
ImageNameWithDigestFile: c.String("image-name-with-digest-file"),
ImageNameTagWithDigestFile: c.String("image-name-tag-with-digest-file"),
Insecure: c.Bool("insecure"),
InsecurePull: c.Bool("insecure-pull"),
InsecureRegistry: c.String("insecure-registry"),
Label: c.String("label"),
LogFormat: c.String("log-format"),
LogTimestamp: c.Bool("log-timestamp"),
OCILayoutPath: c.String("oci-layout-path"),
PushRetry: c.Int("push-retry"),
RegistryCertificate: c.String("registry-certificate"),
RegistryClientCert: c.String("registry-client-cert"),
SkipDefaultRegistryFallback: c.Bool("skip-default-registry-fallback"),
Reproducible: c.Bool("reproducible"),
SingleSnapshot: c.Bool("single-snapshot"),
SkipTLSVerify: c.Bool("skip-tls-verify"),
SkipPushPermissionCheck: c.Bool("skip-push-permission-check"),
SkipTLSVerifyPull: c.Bool("skip-tls-verify-pull"),
SkipTLSVerifyRegistry: c.Bool("skip-tls-verify-registry"),
UseNewRun: c.Bool("use-new-run"),
IgnorePath: c.String("ignore-path"),
IgnorePaths: c.StringSlice("ignore-paths"),
ImageFSExtractRetry: c.Int("image-fs-extract-retry"),
ImageDownloadRetry: c.Int("image-download-retry"),
},
Artifact: kaniko.Artifact{
Tags: c.StringSlice("tags"),
@@ -334,44 +530,77 @@ func run(c *cli.Context) error {
RegistryType: artifact.ECR,
},
}
if c.IsSet("compressed-caching") {
flag := c.Bool("compressed-caching")
plugin.Build.CompressedCaching = &flag
}
if c.IsSet("ignore-var-run") {
flag := c.Bool("ignore-var-run")
plugin.Build.IgnoreVarRun = &flag
}
return plugin.Exec()
}
func createDockerConfig(dockerRegistry, dockerUsername, dockerPassword, accessKey, secretKey,
registry, assumeRole, externalId, region string, noPush bool) (*docker.Config, error) {
func setDockerAuth(dockerRegistry, dockerUsername, dockerPassword, accessKey, secretKey,
registry, assumeRole, externalId, region string, noPush bool, oidcToken string) error {
dockerConfig := docker.NewConfig()
if dockerUsername != "" {
// if no docker registry provided, use dockerhub by default
if len(dockerRegistry) == 0 {
dockerRegistry = docker.RegistryV1
credentials := []docker.RegistryCredentials{}
// set docker credentials for base image registry
if dockerRegistry != "" {
pullFromRegistryCreds := docker.RegistryCredentials{
Registry: dockerRegistry,
Username: dockerUsername,
Password: dockerPassword,
}
dockerConfig.SetAuth(dockerRegistry, dockerUsername, dockerPassword)
credentials = append(credentials, pullFromRegistryCreds)
}
if assumeRole != "" {
if assumeRole != "" && oidcToken != "" {
oidcAccessKey, oidcSecretKey, oidcSessionKey, err := getOidcCreds(oidcToken, assumeRole)
if err != nil {
return err
}
_ = os.Setenv(accessKeyEnv, oidcAccessKey)
_ = os.Setenv(secretKeyEnv, oidcSecretKey)
_ = os.Setenv(sessionKeyEnv, oidcSessionKey)
// kaniko-executor >=1.8.0 does not require additional cred helper logic for ECR,
// as it discovers ECR repositories automatically and acts accordingly.
if isKanikoVersionBelowOneDotEight(os.Getenv(kanikoVersionEnv)) {
dockerConfig.SetCredHelper(ecrPublicDomain, "ecr-login")
dockerConfig.SetCredHelper(registry, "ecr-login")
}
} else if assumeRole != "" {
var err error
username, password, registry, err := getAssumeRoleCreds(region, assumeRole, externalId, "")
if err != nil {
return nil, err
return err
}
dockerConfig.SetAuth(registry, username, password)
pushToRegistryCreds := docker.RegistryCredentials{
Registry: registry,
Username: username,
Password: password,
}
credentials = append(credentials, pushToRegistryCreds)
} else if !noPush || accessKey != "" {
// only setup auth when pushing or credentials are defined
if registry == "" {
return nil, fmt.Errorf("registry must be specified")
return fmt.Errorf("registry must be specified")
}
// If IAM role is used, access key & secret key are not required
if accessKey != "" && secretKey != "" {
err := os.Setenv(accessKeyEnv, accessKey)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("failed to set %s environment variable", accessKeyEnv))
return errors.Wrap(err, fmt.Sprintf("failed to set %s environment variable", accessKeyEnv))
}
err = os.Setenv(secretKeyEnv, secretKey)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("failed to set %s environment variable", secretKeyEnv))
return errors.Wrap(err, fmt.Sprintf("failed to set %s environment variable", secretKeyEnv))
}
}
@@ -382,8 +611,7 @@ func createDockerConfig(dockerRegistry, dockerUsername, dockerPassword, accessKe
dockerConfig.SetCredHelper(registry, "ecr-login")
}
}
return dockerConfig, nil
return dockerConfig.CreateDockerConfig(credentials, dockerConfigPath)
}
func createRepository(region, repo, registry, assumeRole, externalId string) error {
@@ -584,3 +812,37 @@ func isKanikoVersionBelowOneDotEight(v string) bool {
return currVer.LessThan(oneEightVer)
}
func getOidcCreds(oidcToken, assumeRole string) (string, string, string, error) {
// Create a new session
sess, err := session.NewSession()
if err != nil {
return "", "", "", fmt.Errorf("failed to create AWS session: %w", err)
}
// Create a new STS client
svc := sts.New(sess)
// Prepare the input parameters for the STS call
duration := int64(time.Hour / time.Second)
input := &sts.AssumeRoleWithWebIdentityInput{
RoleArn: aws.String(assumeRole),
RoleSessionName: aws.String("kaniko-ecr-oidc"),
WebIdentityToken: aws.String(oidcToken),
DurationSeconds: aws.Int64(duration),
}
// Call the AssumeRoleWithWebIdentity function
result, err := svc.AssumeRoleWithWebIdentity(input)
if err != nil {
return "", "", "", fmt.Errorf("failed to assume role with web identity: %w", err)
}
// Check if credentials exist in the result
if result.Credentials == nil {
return "", "", "", errors.New("no credentials returned by AssumeRoleWithWebIdentity")
}
// Return the credentials
return *result.Credentials.AccessKeyId, *result.Credentials.SecretAccessKey, *result.Credentials.SessionToken, nil
}
+32 -116
View File
@@ -1,129 +1,45 @@
package main
import (
"encoding/base64"
"io/ioutil"
"os"
"reflect"
"testing"
"github.com/drone/drone-kaniko/pkg/docker"
"github.com/stretchr/testify/assert"
)
func TestCreateDockerConfig(t *testing.T) {
got, err := createDockerConfig(
"",
"docker-username",
"docker-password",
"access-key",
"secret-key",
"ecr-registry",
"",
"",
"",
false,
)
if err != nil {
t.Error("failed to create docker config")
func TestCreateDockerConfigForECRWithBaseRegistry(t *testing.T) {
accessKey := "access-key"
secretKey := "secret-key"
ecrRegistry := "ecr-registry"
dockerUsername := "dockeruser"
dockerPassword := "dockerpass"
dockerRegistry := "https://index.docker.io/v1/"
tempDir, err := ioutil.TempDir("", "docker-config-test")
assert.NoError(t, err)
defer os.RemoveAll(tempDir)
config := docker.NewConfig()
pullFromRegistryCreds := docker.RegistryCredentials{
Registry: dockerRegistry,
Username: dockerUsername,
Password: dockerPassword,
}
credentials := []docker.RegistryCredentials{
{Registry: ecrRegistry, Username: accessKey, Password: secretKey},
pullFromRegistryCreds,
}
want := docker.NewConfig()
want.SetAuth(docker.RegistryV1, "docker-username", "docker-password")
want.SetCredHelper(docker.RegistryECRPublic, "ecr-login")
want.SetCredHelper("ecr-registry", "ecr-login")
err = config.CreateDockerConfig(credentials, tempDir)
assert.NoError(t, err)
if !reflect.DeepEqual(want, got) {
t.Errorf("not equal:\n want: %#v\n got: %#v", want, got)
}
}
expectedECRAuth := docker.Auth{Auth: base64.StdEncoding.EncodeToString([]byte(accessKey + ":" + secretKey))}
assert.Equal(t, expectedECRAuth, config.Auths[ecrRegistry])
func TestCreateDockerConfigFromGivenRegistry(t *testing.T) {
got, err := createDockerConfig(
"docker-registry",
"docker-username",
"docker-password",
"access-key",
"secret-key",
"ecr-registry",
"",
"",
"",
false,
)
if err != nil {
t.Error("failed to create docker config")
}
want := docker.NewConfig()
want.SetAuth("docker-registry", "docker-username", "docker-password")
want.SetCredHelper(docker.RegistryECRPublic, "ecr-login")
want.SetCredHelper("ecr-registry", "ecr-login")
if !reflect.DeepEqual(want, got) {
t.Errorf("not equal:\n want: %#v\n got: %#v", want, got)
}
}
func TestCreateDockerConfigKanikoOneDotEight(t *testing.T) {
os.Setenv(kanikoVersionEnv, "1.8.1")
defer os.Setenv(kanikoVersionEnv, "")
got, err := createDockerConfig(
"",
"docker-username",
"docker-password",
"access-key",
"secret-key",
"ecr-registry",
"",
"",
"",
false,
)
if err != nil {
t.Error("failed to create docker config")
}
want := docker.NewConfig()
want.SetAuth(docker.RegistryV1, "docker-username", "docker-password")
if !reflect.DeepEqual(want, got) {
t.Errorf("not equal:\n want: %#v\n got: %#v", want, got)
}
}
func TestVersionComparison(t *testing.T) {
tests := []struct {
title string
version string
expected bool
}{
{
title: "Kaniko 1.6.0 version",
version: "1.6.0",
expected: true,
},
{
title: "Kaniko 1.8.0 version",
version: "1.8.0",
expected: false,
},
{
title: "Kaniko 1.8.1 version",
version: "1.8.1",
expected: false,
},
{
title: "Empty kaniko version",
version: "",
expected: true,
},
{
title: "Kaniko version 1.10.0",
version: "1.10.0",
expected: false,
},
}
for _, test := range tests {
got := isKanikoVersionBelowOneDotEight(test.version)
if got != test.expected {
t.Fatalf("test name: %s, expected: %v, got: %v", test.title, test.expected, got)
}
}
}
expectedDockerAuth := docker.Auth{Auth: base64.StdEncoding.EncodeToString([]byte(dockerUsername + ":" + dockerPassword))}
assert.Equal(t, expectedDockerAuth, config.Auths[dockerRegistry])
}
+254 -25
View File
@@ -12,12 +12,14 @@ import (
kaniko "github.com/drone/drone-kaniko"
"github.com/drone/drone-kaniko/pkg/artifact"
"github.com/drone/drone-kaniko/pkg/docker"
)
const (
dockerConfigPath string = "/kaniko/.docker"
// GAR JSON key file path
garKeyPath string = "/kaniko/config.json"
garEnvVariable string = "GOOGLE_APPLICATION_CREDENTIALS"
garKeyPath string = "/kaniko/config.json"
garEnvVariable string = "GOOGLE_APPLICATION_CREDENTIALS"
defaultDigestFile string = "/kaniko/digest-file"
)
@@ -109,6 +111,21 @@ func main() {
Usage: "gar registry",
EnvVar: "PLUGIN_REGISTRY",
},
cli.StringFlag{
Name: "base-image-username",
Usage: "Docker username for base image registry",
EnvVar: "PLUGIN_DOCKER_USERNAME,PLUGIN_BASE_IMAGE_USERNAME,DOCKER_USERNAME",
},
cli.StringFlag{
Name: "base-image-password",
Usage: "Docker password for base image registry",
EnvVar: "PLUGIN_DOCKER_PASSWORD,PLUGIN_BASE_IMAGE_PASSWORD,DOCKER_PASSWORD",
},
cli.StringFlag{
Name: "base-image-registry",
Usage: "Docker registry for base image registry",
EnvVar: "PLUGIN_DOCKER_REGISTRY,PLUGIN_BASE_IMAGE_REGISTRY,DOCKER_REGISTRY",
},
cli.StringSliceFlag{
Name: "registry-mirrors",
Usage: "docker registry mirrors",
@@ -164,6 +181,157 @@ func main() {
Usage: "build only used stages",
EnvVar: "PLUGIN_SKIP_UNUSED_STAGES",
},
cli.StringFlag{
Name: "cache-dir",
Usage: "Set this flag to specify a local directory cache for base images",
EnvVar: "PLUGIN_CACHE_DIR",
},
cli.BoolFlag{
Name: "cache-copy-layers",
Usage: "Enable or disable copying layers from the cache.",
EnvVar: "PLUGIN_CACHE_COPY_LAYERS",
},
cli.BoolFlag{
Name: "cache-run-layers",
Usage: "Enable or disable running layers from the cache.",
EnvVar: "PLUGIN_CACHE_RUN_LAYERS",
},
cli.BoolFlag{
Name: "cleanup",
Usage: "Enable or disable cleanup of temporary files.",
EnvVar: "PLUGIN_CLEANUP",
},
cli.BoolFlag{
Name: "compressed-caching",
Usage: "Enable or disable compressed caching.",
EnvVar: "PLUGIN_COMPRESSED_CACHING",
},
cli.StringFlag{
Name: "context-sub-path",
Usage: "Sub-path within the context to build.",
EnvVar: "PLUGIN_CONTEXT_SUB_PATH",
},
cli.StringFlag{
Name: "custom-platform",
Usage: "Platform to use for building.",
EnvVar: "PLUGIN_CUSTOM_PLATFORM",
},
cli.BoolFlag{
Name: "force",
Usage: "Force building the image even if it already exists.",
EnvVar: "PLUGIN_FORCE",
},
cli.StringFlag{
Name: "image-name-with-digest-file",
Usage: "Write image name with digest to a file.",
EnvVar: "PLUGIN_IMAGE_NAME_WITH_DIGEST_FILE",
},
cli.StringFlag{
Name: "image-name-tag-with-digest-file",
Usage: "Write image name with tag and digest to a file.",
EnvVar: "PLUGIN_IMAGE_NAME_TAG_WITH_DIGEST_FILE",
},
cli.BoolFlag{
Name: "insecure",
Usage: "Allow connecting to registries without TLS.",
EnvVar: "PLUGIN_INSECURE",
},
cli.BoolFlag{
Name: "insecure-pull",
Usage: "Allow insecure pulls from the registry.",
EnvVar: "PLUGIN_INSECURE_PULL",
},
cli.StringFlag{
Name: "insecure-registry",
Usage: "Use plain HTTP for registry communication.",
EnvVar: "PLUGIN_INSECURE_REGISTRY",
},
cli.StringFlag{
Name: "log-format",
Usage: "Set the log format for build output.",
EnvVar: "PLUGIN_LOG_FORMAT",
},
cli.BoolFlag{
Name: "log-timestamp",
Usage: "Show timestamps in build output.",
EnvVar: "PLUGIN_LOG_TIMESTAMP",
},
cli.StringFlag{
Name: "oci-layout-path",
Usage: "Directory to store OCI layout.",
EnvVar: "PLUGIN_OCI_LAYOUT_PATH",
},
cli.IntFlag{
Name: "push-retry",
Usage: "Number of times to retry pushing an image.",
EnvVar: "PLUGIN_PUSH_RETRY",
},
cli.StringFlag{
Name: "registry-certificate",
Usage: "Path to a file containing a registry certificate.",
EnvVar: "PLUGIN_REGISTRY_CERTIFICATE",
},
cli.StringFlag{
Name: "registry-client-cert",
Usage: "Path to a file containing a registry client certificate.",
EnvVar: "PLUGIN_REGISTRY_CLIENT_CERT",
},
cli.BoolFlag{
Name: "skip-default-registry-fallback",
Usage: "Skip Docker Hub and default registry fallback.",
EnvVar: "PLUGIN_SKIP_DEFAULT_REGISTRY_FALLBACK",
},
cli.BoolFlag{
Name: "reproducible",
Usage: "Create a reproducible image.",
EnvVar: "PLUGIN_REPRODUCIBLE",
},
cli.BoolFlag{
Name: "single-snapshot",
Usage: "Only create a single snapshot of the image.",
EnvVar: "PLUGIN_SINGLE_SNAPSHOT",
},
cli.BoolFlag{
Name: "skip-push-permission-check",
Usage: "Skip permission check when pushing.",
EnvVar: "PLUGIN_SKIP_PUSH_PERMISSION_CHECK",
},
cli.BoolFlag{
Name: "skip-tls-verify-pull",
Usage: "Skip TLS verification when pulling.",
EnvVar: "PLUGIN_SKIP_TLS_VERIFY_PULL",
},
cli.BoolFlag{
Name: "skip-tls-verify-registry",
Usage: "Skip TLS verification when connecting to a registry.",
EnvVar: "PLUGIN_SKIP_TLS_VERIFY_REGISTRY",
},
cli.BoolFlag{
Name: "use-new-run",
Usage: "Skip TLS verification when connecting to a registry.",
EnvVar: "PLUGIN_USE_NEW_RUN",
},
cli.BoolFlag{
Name: "ignore-var-run",
Usage: "Ignore the /var/run directory during build.",
EnvVar: "PLUGIN_IGNORE_VAR_RUN",
},
cli.StringFlag{
Name: "ignore-path",
Usage: "Path to ignore during the build.",
EnvVar: "PLUGIN_IGNORE_PATH",
},
cli.IntFlag{
Name: "image-fs-extract-retry",
Usage: "Number of retries for extracting filesystem layers.",
EnvVar: "PLUGIN_IMAGE_FS_EXTRACT_RETRY",
},
cli.IntFlag{
Name: "image-download-retry",
Usage: "Number of retries for downloading base images.",
EnvVar: "PLUGIN_IMAGE_DOWNLOAD_RETRY",
},
}
if err := app.Run(os.Args); err != nil {
@@ -174,7 +342,6 @@ func main() {
func run(c *cli.Context) error {
noPush := c.Bool("no-push")
jsonKey := c.String("json-key")
// JSON key may not be set in the following cases:
// 1. Image does not need to be pushed to GAR.
// 2. Workload identity is set on GKE in which pod will inherit the credentials via service account.
@@ -182,32 +349,74 @@ func run(c *cli.Context) error {
if err := setupGARAuth(jsonKey); err != nil {
return err
}
// setup docker config only when base image registry is specified
if c.String("base-image-registry") != ""{
if err := setDockerAuth(
c.String("base-image-username"),
c.String("base-image-password"),
c.String("base-image-registry"),
); err != nil {
return errors.Wrap(err, "failed to create docker config")
}
}
}
plugin := kaniko.Plugin{
Build: kaniko.Build{
DroneCommitRef: c.String("drone-commit-ref"),
DroneRepoBranch: c.String("drone-repo-branch"),
Dockerfile: c.String("dockerfile"),
Context: c.String("context"),
Tags: c.StringSlice("tags"),
AutoTag: c.Bool("auto-tag"),
AutoTagSuffix: c.String("auto-tag-suffix"),
ExpandTag: c.Bool("expand-tag"),
Args: c.StringSlice("args"),
Target: c.String("target"),
Repo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("repo")),
Mirrors: c.StringSlice("registry-mirrors"),
Labels: c.StringSlice("custom-labels"),
SnapshotMode: c.String("snapshot-mode"),
EnableCache: c.Bool("enable-cache"),
CacheRepo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("cache-repo")),
CacheTTL: c.Int("cache-ttl"),
DigestFile: defaultDigestFile,
NoPush: noPush,
Verbosity: c.String("verbosity"),
Platform: c.String("platform"),
SkipUnusedStages: c.Bool("skip-unused-stages"),
DroneCommitRef: c.String("drone-commit-ref"),
DroneRepoBranch: c.String("drone-repo-branch"),
Dockerfile: c.String("dockerfile"),
Context: c.String("context"),
Tags: c.StringSlice("tags"),
AutoTag: c.Bool("auto-tag"),
AutoTagSuffix: c.String("auto-tag-suffix"),
ExpandTag: c.Bool("expand-tag"),
Args: c.StringSlice("args"),
Target: c.String("target"),
Repo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("repo")),
Mirrors: c.StringSlice("registry-mirrors"),
Labels: c.StringSlice("custom-labels"),
SnapshotMode: c.String("snapshot-mode"),
EnableCache: c.Bool("enable-cache"),
CacheRepo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("cache-repo")),
CacheTTL: c.Int("cache-ttl"),
DigestFile: defaultDigestFile,
NoPush: noPush,
Verbosity: c.String("verbosity"),
Platform: c.String("platform"),
SkipUnusedStages: c.Bool("skip-unused-stages"),
CacheDir: c.String("cache-dir"),
CacheCopyLayers: c.Bool("cache-copy-layers"),
CacheRunLayers: c.Bool("cache-run-layers"),
Cleanup: c.Bool("cleanup"),
ContextSubPath: c.String("context-sub-path"),
CustomPlatform: c.String("custom-platform"),
Force: c.Bool("force"),
ImageNameWithDigestFile: c.String("image-name-with-digest-file"),
ImageNameTagWithDigestFile: c.String("image-name-tag-with-digest-file"),
Insecure: c.Bool("insecure"),
InsecurePull: c.Bool("insecure-pull"),
InsecureRegistry: c.String("insecure-registry"),
Label: c.String("label"),
LogFormat: c.String("log-format"),
LogTimestamp: c.Bool("log-timestamp"),
OCILayoutPath: c.String("oci-layout-path"),
PushRetry: c.Int("push-retry"),
RegistryCertificate: c.String("registry-certificate"),
RegistryClientCert: c.String("registry-client-cert"),
SkipDefaultRegistryFallback: c.Bool("skip-default-registry-fallback"),
Reproducible: c.Bool("reproducible"),
SingleSnapshot: c.Bool("single-snapshot"),
SkipTLSVerify: c.Bool("skip-tls-verify"),
SkipPushPermissionCheck: c.Bool("skip-push-permission-check"),
SkipTLSVerifyPull: c.Bool("skip-tls-verify-pull"),
SkipTLSVerifyRegistry: c.Bool("skip-tls-verify-registry"),
UseNewRun: c.Bool("use-new-run"),
IgnorePath: c.String("ignore-path"),
IgnorePaths: c.StringSlice("ignore-paths"),
ImageFSExtractRetry: c.Int("image-fs-extract-retry"),
ImageDownloadRetry: c.Int("image-download-retry"),
},
Artifact: kaniko.Artifact{
Tags: c.StringSlice("tags"),
@@ -217,9 +426,29 @@ func run(c *cli.Context) error {
RegistryType: artifact.GAR,
},
}
if c.IsSet("compressed-caching") {
flag := c.Bool("compressed-caching")
plugin.Build.CompressedCaching = &flag
}
if c.IsSet("ignore-var-run") {
flag := c.Bool("ignore-var-run")
plugin.Build.IgnoreVarRun = &flag
}
return plugin.Exec()
}
func setDockerAuth(dockerUsername, dockerPassword, dockerRegistry string) (error) {
dockerConfig := docker.NewConfig()
dockerRegistryCreds := docker.RegistryCredentials{
Registry: dockerRegistry,
Username: dockerUsername,
Password: dockerPassword,
}
credentials := []docker.RegistryCredentials{dockerRegistryCreds}
return dockerConfig.CreateDockerConfig(credentials, dockerConfigPath)
}
func setupGARAuth(jsonKey string) error {
err := ioutil.WriteFile(garKeyPath, []byte(jsonKey), 0644)
if err != nil {
+254 -25
View File
@@ -12,12 +12,14 @@ import (
kaniko "github.com/drone/drone-kaniko"
"github.com/drone/drone-kaniko/pkg/artifact"
"github.com/drone/drone-kaniko/pkg/docker"
)
const (
dockerConfigPath string = "/kaniko/.docker"
// GCR JSON key file path
gcrKeyPath string = "/kaniko/config.json"
gcrEnvVariable string = "GOOGLE_APPLICATION_CREDENTIALS"
gcrKeyPath string = "/kaniko/config.json"
gcrEnvVariable string = "GOOGLE_APPLICATION_CREDENTIALS"
defaultDigestFile string = "/kaniko/digest-file"
)
@@ -108,7 +110,22 @@ func main() {
Name: "registry",
Usage: "gcr registry",
Value: "gcr.io",
EnvVar: "PLUGIN_REGISTRY",
EnvVar: "PLUGIN_REGISTRY,BASE_REGISTRY",
},
cli.StringFlag{
Name: "base-image-username",
Usage: "Docker username for base image registry",
EnvVar: "PLUGIN_DOCKER_USERNAME,PLUGIN_BASE_IMAGE_USERNAME,DOCKER_USERNAME",
},
cli.StringFlag{
Name: "base-image-password",
Usage: "Docker password for base image registry",
EnvVar: "PLUGIN_DOCKER_PASSWORD,PLUGIN_BASE_IMAGE_PASSWORD,DOCKER_PASSWORD",
},
cli.StringFlag{
Name: "base-image-registry",
Usage: "Docker registry for base image registry",
EnvVar: "PLUGIN_DOCKER_REGISTRY,PLUGIN_BASE_IMAGE_REGISTRY,DOCKER_REGISTRY",
},
cli.StringSliceFlag{
Name: "registry-mirrors",
@@ -165,6 +182,157 @@ func main() {
Usage: "build only used stages",
EnvVar: "PLUGIN_SKIP_UNUSED_STAGES",
},
cli.StringFlag{
Name: "cache-dir",
Usage: "Set this flag to specify a local directory cache for base images",
EnvVar: "PLUGIN_CACHE_DIR",
},
cli.BoolFlag{
Name: "cache-copy-layers",
Usage: "Enable or disable copying layers from the cache.",
EnvVar: "PLUGIN_CACHE_COPY_LAYERS",
},
cli.BoolFlag{
Name: "cache-run-layers",
Usage: "Enable or disable running layers from the cache.",
EnvVar: "PLUGIN_CACHE_RUN_LAYERS",
},
cli.BoolFlag{
Name: "cleanup",
Usage: "Enable or disable cleanup of temporary files.",
EnvVar: "PLUGIN_CLEANUP",
},
cli.BoolFlag{
Name: "compressed-caching",
Usage: "Enable or disable compressed caching.",
EnvVar: "PLUGIN_COMPRESSED_CACHING",
},
cli.StringFlag{
Name: "context-sub-path",
Usage: "Sub-path within the context to build.",
EnvVar: "PLUGIN_CONTEXT_SUB_PATH",
},
cli.StringFlag{
Name: "custom-platform",
Usage: "Platform to use for building.",
EnvVar: "PLUGIN_CUSTOM_PLATFORM",
},
cli.BoolFlag{
Name: "force",
Usage: "Force building the image even if it already exists.",
EnvVar: "PLUGIN_FORCE",
},
cli.StringFlag{
Name: "image-name-with-digest-file",
Usage: "Write image name with digest to a file.",
EnvVar: "PLUGIN_IMAGE_NAME_WITH_DIGEST_FILE",
},
cli.StringFlag{
Name: "image-name-tag-with-digest-file",
Usage: "Write image name with tag and digest to a file.",
EnvVar: "PLUGIN_IMAGE_NAME_TAG_WITH_DIGEST_FILE",
},
cli.BoolFlag{
Name: "insecure",
Usage: "Allow connecting to registries without TLS.",
EnvVar: "PLUGIN_INSECURE",
},
cli.BoolFlag{
Name: "insecure-pull",
Usage: "Allow insecure pulls from the registry.",
EnvVar: "PLUGIN_INSECURE_PULL",
},
cli.StringFlag{
Name: "insecure-registry",
Usage: "Use plain HTTP for registry communication.",
EnvVar: "PLUGIN_INSECURE_REGISTRY",
},
cli.StringFlag{
Name: "log-format",
Usage: "Set the log format for build output.",
EnvVar: "PLUGIN_LOG_FORMAT",
},
cli.BoolFlag{
Name: "log-timestamp",
Usage: "Show timestamps in build output.",
EnvVar: "PLUGIN_LOG_TIMESTAMP",
},
cli.StringFlag{
Name: "oci-layout-path",
Usage: "Directory to store OCI layout.",
EnvVar: "PLUGIN_OCI_LAYOUT_PATH",
},
cli.IntFlag{
Name: "push-retry",
Usage: "Number of times to retry pushing an image.",
EnvVar: "PLUGIN_PUSH_RETRY",
},
cli.StringFlag{
Name: "registry-certificate",
Usage: "Path to a file containing a registry certificate.",
EnvVar: "PLUGIN_REGISTRY_CERTIFICATE",
},
cli.StringFlag{
Name: "registry-client-cert",
Usage: "Path to a file containing a registry client certificate.",
EnvVar: "PLUGIN_REGISTRY_CLIENT_CERT",
},
cli.BoolFlag{
Name: "skip-default-registry-fallback",
Usage: "Skip Docker Hub and default registry fallback.",
EnvVar: "PLUGIN_SKIP_DEFAULT_REGISTRY_FALLBACK",
},
cli.BoolFlag{
Name: "reproducible",
Usage: "Create a reproducible image.",
EnvVar: "PLUGIN_REPRODUCIBLE",
},
cli.BoolFlag{
Name: "single-snapshot",
Usage: "Only create a single snapshot of the image.",
EnvVar: "PLUGIN_SINGLE_SNAPSHOT",
},
cli.BoolFlag{
Name: "skip-push-permission-check",
Usage: "Skip permission check when pushing.",
EnvVar: "PLUGIN_SKIP_PUSH_PERMISSION_CHECK",
},
cli.BoolFlag{
Name: "skip-tls-verify-pull",
Usage: "Skip TLS verification when pulling.",
EnvVar: "PLUGIN_SKIP_TLS_VERIFY_PULL",
},
cli.BoolFlag{
Name: "skip-tls-verify-registry",
Usage: "Skip TLS verification when connecting to a registry.",
EnvVar: "PLUGIN_SKIP_TLS_VERIFY_REGISTRY",
},
cli.BoolFlag{
Name: "use-new-run",
Usage: "Skip TLS verification when connecting to a registry.",
EnvVar: "PLUGIN_USE_NEW_RUN",
},
cli.BoolFlag{
Name: "ignore-var-run",
Usage: "Ignore the /var/run directory during build.",
EnvVar: "PLUGIN_IGNORE_VAR_RUN",
},
cli.StringFlag{
Name: "ignore-path",
Usage: "Path to ignore during the build.",
EnvVar: "PLUGIN_IGNORE_PATH",
},
cli.IntFlag{
Name: "image-fs-extract-retry",
Usage: "Number of retries for extracting filesystem layers.",
EnvVar: "PLUGIN_IMAGE_FS_EXTRACT_RETRY",
},
cli.IntFlag{
Name: "image-download-retry",
Usage: "Number of retries for downloading base images.",
EnvVar: "PLUGIN_IMAGE_DOWNLOAD_RETRY",
},
}
if err := app.Run(os.Args); err != nil {
@@ -183,32 +351,74 @@ func run(c *cli.Context) error {
if err := setupGCRAuth(jsonKey); err != nil {
return err
}
// setup docker config only when base image registry is specified
if c.String("base-image-registry") != ""{
if err := setDockerAuth(
c.String("base-image-username"),
c.String("base-image-password"),
c.String("base-image-registry"),
); err != nil {
return errors.Wrap(err, "failed to create docker config")
}
}
}
plugin := kaniko.Plugin{
Build: kaniko.Build{
DroneCommitRef: c.String("drone-commit-ref"),
DroneRepoBranch: c.String("drone-repo-branch"),
Dockerfile: c.String("dockerfile"),
Context: c.String("context"),
Tags: c.StringSlice("tags"),
AutoTag: c.Bool("auto-tag"),
AutoTagSuffix: c.String("auto-tag-suffix"),
ExpandTag: c.Bool("expand-tag"),
Args: c.StringSlice("args"),
Target: c.String("target"),
Repo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("repo")),
Mirrors: c.StringSlice("registry-mirrors"),
Labels: c.StringSlice("custom-labels"),
SnapshotMode: c.String("snapshot-mode"),
EnableCache: c.Bool("enable-cache"),
CacheRepo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("cache-repo")),
CacheTTL: c.Int("cache-ttl"),
DigestFile: defaultDigestFile,
NoPush: noPush,
Verbosity: c.String("verbosity"),
Platform: c.String("platform"),
SkipUnusedStages: c.Bool("skip-unused-stages"),
DroneCommitRef: c.String("drone-commit-ref"),
DroneRepoBranch: c.String("drone-repo-branch"),
Dockerfile: c.String("dockerfile"),
Context: c.String("context"),
Tags: c.StringSlice("tags"),
AutoTag: c.Bool("auto-tag"),
AutoTagSuffix: c.String("auto-tag-suffix"),
ExpandTag: c.Bool("expand-tag"),
Args: c.StringSlice("args"),
Target: c.String("target"),
Repo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("repo")),
Mirrors: c.StringSlice("registry-mirrors"),
Labels: c.StringSlice("custom-labels"),
SnapshotMode: c.String("snapshot-mode"),
EnableCache: c.Bool("enable-cache"),
CacheRepo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("cache-repo")),
CacheTTL: c.Int("cache-ttl"),
DigestFile: defaultDigestFile,
NoPush: noPush,
Verbosity: c.String("verbosity"),
Platform: c.String("platform"),
SkipUnusedStages: c.Bool("skip-unused-stages"),
CacheDir: c.String("cache-dir"),
CacheCopyLayers: c.Bool("cache-copy-layers"),
CacheRunLayers: c.Bool("cache-run-layers"),
Cleanup: c.Bool("cleanup"),
ContextSubPath: c.String("context-sub-path"),
CustomPlatform: c.String("custom-platform"),
Force: c.Bool("force"),
ImageNameWithDigestFile: c.String("image-name-with-digest-file"),
ImageNameTagWithDigestFile: c.String("image-name-tag-with-digest-file"),
Insecure: c.Bool("insecure"),
InsecurePull: c.Bool("insecure-pull"),
InsecureRegistry: c.String("insecure-registry"),
Label: c.String("label"),
LogFormat: c.String("log-format"),
LogTimestamp: c.Bool("log-timestamp"),
OCILayoutPath: c.String("oci-layout-path"),
PushRetry: c.Int("push-retry"),
RegistryCertificate: c.String("registry-certificate"),
RegistryClientCert: c.String("registry-client-cert"),
SkipDefaultRegistryFallback: c.Bool("skip-default-registry-fallback"),
Reproducible: c.Bool("reproducible"),
SingleSnapshot: c.Bool("single-snapshot"),
SkipTLSVerify: c.Bool("skip-tls-verify"),
SkipPushPermissionCheck: c.Bool("skip-push-permission-check"),
SkipTLSVerifyPull: c.Bool("skip-tls-verify-pull"),
SkipTLSVerifyRegistry: c.Bool("skip-tls-verify-registry"),
UseNewRun: c.Bool("use-new-run"),
IgnorePath: c.String("ignore-path"),
IgnorePaths: c.StringSlice("ignore-paths"),
ImageFSExtractRetry: c.Int("image-fs-extract-retry"),
ImageDownloadRetry: c.Int("image-download-retry"),
},
Artifact: kaniko.Artifact{
Tags: c.StringSlice("tags"),
@@ -218,9 +428,28 @@ func run(c *cli.Context) error {
RegistryType: artifact.GCR,
},
}
if c.IsSet("compressed-caching") {
flag := c.Bool("compressed-caching")
plugin.Build.CompressedCaching = &flag
}
if c.IsSet("ignore-var-run") {
flag := c.Bool("ignore-var-run")
plugin.Build.IgnoreVarRun = &flag
}
return plugin.Exec()
}
func setDockerAuth(dockerUsername, dockerPassword, dockerRegistry string) (error) {
dockerConfig := docker.NewConfig()
dockerRegistryCreds := docker.RegistryCredentials{
Registry: dockerRegistry,
Username: dockerUsername,
Password: dockerPassword,
}
credentials := []docker.RegistryCredentials{dockerRegistryCreds}
return dockerConfig.CreateDockerConfig(credentials, dockerConfigPath)
}
func setupGCRAuth(jsonKey string) error {
err := ioutil.WriteFile(gcrKeyPath, []byte(jsonKey), 0644)
if err != nil {
+2 -2
View File
@@ -1,5 +1,5 @@
FROM gcr.io/kaniko-project/executor:v1.19.2
FROM gcr.io/kaniko-project/executor:v1.23.2
ENV KANIKO_VERSION=1.19.2
ENV KANIKO_VERSION=1.23.2
ADD release/linux/amd64/kaniko-acr /kaniko/
ENTRYPOINT ["/kaniko/kaniko-acr"]
+2 -2
View File
@@ -1,8 +1,8 @@
FROM gcr.io/kaniko-project/executor:v1.19.2
FROM gcr.io/kaniko-project/executor:v1.23.0
ENV HOME /root
ENV USER root
ENV KANIKO_VERSION=1.19.2
ENV KANIKO_VERSION=1.23.0
ADD release/linux/arm64/kaniko-acr /kaniko/
ENTRYPOINT ["/kaniko/kaniko-acr"]
+2 -2
View File
@@ -1,5 +1,5 @@
FROM gcr.io/kaniko-project/executor:v1.19.2
FROM gcr.io/kaniko-project/executor:v1.23.2
ENV KANIKO_VERSION=1.19.2
ENV KANIKO_VERSION=1.23.2
ADD release/linux/amd64/kaniko-docker /kaniko/
ENTRYPOINT ["/kaniko/kaniko-docker"]
+2 -2
View File
@@ -1,8 +1,8 @@
FROM gcr.io/kaniko-project/executor:v1.19.2
FROM gcr.io/kaniko-project/executor:v1.23.2
ENV HOME /root
ENV USER root
ENV KANIKO_VERSION=1.19.2
ENV KANIKO_VERSION=1.23.2
ADD release/linux/arm64/kaniko-docker /kaniko/
ENTRYPOINT ["/kaniko/kaniko-docker"]
+2 -2
View File
@@ -1,5 +1,5 @@
FROM gcr.io/kaniko-project/executor:v1.19.2
FROM gcr.io/kaniko-project/executor:v1.23.2
ENV KANIKO_VERSION=1.19.2
ENV KANIKO_VERSION=1.23.2
ADD release/linux/amd64/kaniko-ecr /kaniko/
ENTRYPOINT ["/kaniko/kaniko-ecr"]
+2 -2
View File
@@ -1,8 +1,8 @@
FROM gcr.io/kaniko-project/executor:v1.19.2
FROM gcr.io/kaniko-project/executor:v1.23.2
ENV HOME /root
ENV USER root
ENV KANIKO_VERSION=1.19.2
ENV KANIKO_VERSION=1.23.2
ADD release/linux/arm64/kaniko-ecr /kaniko/
ENTRYPOINT ["/kaniko/kaniko-ecr"]
+2 -2
View File
@@ -1,5 +1,5 @@
FROM gcr.io/kaniko-project/executor:v1.19.2
FROM gcr.io/kaniko-project/executor:v1.23.2
ENV KANIKO_VERSION=1.19.2
ENV KANIKO_VERSION=1.23.2
ADD release/linux/amd64/kaniko-gar /kaniko/
ENTRYPOINT ["/kaniko/kaniko-gar"]
+2 -2
View File
@@ -1,8 +1,8 @@
FROM gcr.io/kaniko-project/executor:v1.19.2
FROM gcr.io/kaniko-project/executor:v1.23.2
ENV HOME /root
ENV USER root
ENV KANIKO_VERSION=1.19.2
ENV KANIKO_VERSION=1.23.2
ADD release/linux/arm64/kaniko-gar /kaniko/
ENTRYPOINT ["/kaniko/kaniko-gar"]
+2 -2
View File
@@ -1,5 +1,5 @@
FROM gcr.io/kaniko-project/executor:v1.19.2
FROM gcr.io/kaniko-project/executor:v1.23.2
ENV KANIKO_VERSION=1.19.2
ENV KANIKO_VERSION=1.23.2
ADD release/linux/amd64/kaniko-gcr /kaniko/
ENTRYPOINT ["/kaniko/kaniko-gcr"]
+2 -2
View File
@@ -1,8 +1,8 @@
FROM gcr.io/kaniko-project/executor:v1.19.2
FROM gcr.io/kaniko-project/executor:v1.23.2
ENV HOME /root
ENV USER root
ENV KANIKO_VERSION=1.19.2
ENV KANIKO_VERSION=1.23.2
ADD release/linux/arm64/kaniko-gcr /kaniko/
ENTRYPOINT ["/kaniko/kaniko-gcr"]
View File
+8
View File
@@ -0,0 +1,8 @@
This document explains on how to install certain git hooks globally for all repositories in your machine.
Step 1: git clone https://github.com/drone/drone-kaniko.git
Step 2: cd git-hooks
Step 3: Run install.sh
"install.sh" script will create .git_template in the user directory and will put the git hook and its dependent scripts in it. Along with the .git_template folder, it will add 2 sections "init" and "hooks boolean" in the .gitconfig file in the same user's root directory.
After running "install.sh" if you create/clone a new git repository then all the hooks will get install automatically for the git repository. In case of existing git repository copy the contents of ~/.git_template/hooks into the .git/hooks directory of existing git repository.
+17
View File
@@ -0,0 +1,17 @@
#!/bin/bash
#Helper script to be used as a pre-commit hook.
echo "This hook checks for any secrets getting pushed as part of commit. If you feel that scan is false positive. \
Then add the exclusion in .gitleaksignore file. For more info visit: https://github.com/zricethezav/gitleaks"
GIT_LEAKS_PRE_COMMIT=s$(git config --bool hook.pre-commit.gitleak)
echo "INFO: Scanning Commits information for any GIT LEAKS"
gitleaks protect --staged -v --exit-code=100
STATUS=$?
if [ $STATUS = 100 ]; then
echo "WARNING: GIT LEAKS has detected sensitive information in your changes. Please remove them or add them (IF NON-SENSITIVE) in .gitleaksignore file."
else
exit 0
fi
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
#Helper script to be used as a pre-commit hook.
echo "This hook checks for any secrets getting pushed as part of commit. If you feel that scan is false positive. \
Then add the exclusion in .gitleaksignore file. For more info visit: https://github.com/zricethezav/gitleaks"
GIT_LEAKS=$(git config --bool hook.pre-push.gitleaks)
echo "INFO: Scanning Commits information for any GIT LEAKS"
gitleaks detect -s ./ --log-level=debug --log-opts=-1 -v
STATUS=$?
if [ $STATUS != 0 ]; then
echo "WARNING: GIT LEAKS has detected sensitive information in your changes. Please remove them or add them (IF NON-SENSITIVE) in .gitleaksignore file."
exit $STATUS
else
exit 0
fi
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
GL_SCRIPT_PATH="$HOME/.git_template/hooks/git-leaks-pre-commit.sh"
pushd `dirname $0` > /dev/null && cd ../.. && BASEDIR=$(pwd -L) && popd > /dev/null
BASENAME=`basename $0`
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
#Initial commit : diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
GIT_LEAKS_PRE_COMMIT=hook.pre-commit.gitleaks
if [ "`git config $GIT_LEAKS_PRE_COMMIT`" == "false" ]
then
echo -e '\033[0;31m' checking git leaks is disabled - to enable: '\033[0;37m'git config --unset $GIT_LEAKS_PRE_COMMIT '\033[0m'
echo -e '\033[0;34m' checking git leaks ... to enable: '\033[0;37m'git config --add $GIT_LEAKS_PRE_COMMIT true '\033[0m'
else
echo -e '\033[0;34m' checking for git leaks...
[ -f "${GL_SCRIPT_PATH}" ] && . ${GL_SCRIPT_PATH} || echo "ERROR: Hook Script Not Found..." && exit 404
fi
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
GL_SCRIPT_PATH="$HOME/.git_template/hooks/git-leaks.sh"
pushd `dirname $0` > /dev/null && cd ../.. && BASEDIR=$(pwd -L) && popd > /dev/null
BASENAME=`basename $0`
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
#Initial commit : diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
GIT_LEAKS=hook.pre-push.gitleaks
if [ "`git config $GIT_LEAKS`" == "false" ]
then
echo -e '\033[0;31m' checking git leaks is disabled - to enable: '\033[0;37m'git config --unset $GIT_LEAKS '\033[0m'
echo -e '\033[0;34m' checking git leaks ... to enable: '\033[0;37m'git config --add $GIT_LEAKS true '\033[0m'
else
echo -e '\033[0;34m' checking for git leaks...
[ -f "${GL_SCRIPT_PATH}" ] && . ${GL_SCRIPT_PATH} || echo "ERROR: Hook Script Not Found..." && exit 404
fi
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
#Function to check if package is installed or not
#args: $1: Name of the Package
function check_package_installed() {
LOCAL_PACKAGE_NAME=$1
echo "Checking if $LOCAL_PACKAGE_NAME is installed or not..."
brew list $LOCAL_PACKAGE_NAME
if [ "$?" -eq 1 ];then
echo "Installing $LOCAL_PACKAGE_NAME package..."
brew install $LOCAL_PACKAGE_NAME
fi
}
function create_git_template() {
cd $BASEDIR
mkdir -p ~/.git_template/hooks
git config --global init.templatedir ${GIT_TEMPLATE}
git config --global --add $GIT_LEAKS true
git config --global --add $GIT_LEAKS_PRE_COMMIT true
find hooks/ -type f -exec cp "{}" ~/.git_template/hooks \;
#cp -f hooks/* ~/.git_template/hooks
cat ~/.gitconfig
}
GIT_TEMPLATE="~/.git_template"
GIT_LEAKS=hook.pre-push.gitleaks
GIT_LEAKS_PRE_COMMIT=hook.pre-commit.gitleaks
pushd `dirname $0` && BASEDIR=$(pwd -L) && popd
echo This script will install hooks that run scripts that could be updated without notice.
while true; do
read -p "Do you wish to install these hooks?" yn
case $yn in
[Yy]* ) check_package_installed "gitleaks";
break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
create_git_template
+26 -10
View File
@@ -10,13 +10,15 @@ require (
github.com/aws/aws-sdk-go-v2/service/ecrpublic v1.13.8
github.com/aws/smithy-go v1.12.0
github.com/coreos/go-semver v0.3.0
github.com/google/go-cmp v0.5.8
github.com/google/go-cmp v0.5.9
github.com/google/go-containerregistry v0.20.2
github.com/hashicorp/go-version v1.6.0
github.com/joho/godotenv v1.4.0
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.8.1
github.com/urfave/cli v1.22.9
golang.org/x/mod v0.5.1
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.8.4
github.com/urfave/cli v1.22.12
golang.org/x/mod v0.17.0
)
require (
@@ -30,17 +32,31 @@ require (
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.8 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.11.12 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.16.9 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
github.com/containerd/stargz-snapshotter/estargz v0.14.3 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/docker/cli v27.1.1+incompatible // indirect
github.com/docker/distribution v2.8.2+incompatible // indirect
github.com/docker/docker-credential-helpers v0.7.0 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/klauspost/compress v1.16.5 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.0-rc3 // indirect
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa // indirect
golang.org/x/net v0.0.0-20220725212005-46097bf591d3 // indirect
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect
golang.org/x/text v0.3.7 // indirect
github.com/vbatts/tar-split v0.11.3 // indirect
golang.org/x/crypto v0.14.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sync v0.2.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.13.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
go 1.21
go 1.22.4
+66 -25
View File
@@ -6,7 +6,7 @@ github.com/Azure/azure-sdk-for-go/sdk/internal v1.0.0 h1:jp0dGvZ7ZK0mgqnTSClMxa5
github.com/Azure/azure-sdk-for-go/sdk/internal v1.0.0/go.mod h1:eWRD7oawr1Mu1sLCawqVc0CUiF43ia3qQMxLscsKQ9w=
github.com/AzureAD/microsoft-authentication-library-for-go v0.5.3 h1:TsFCaaF5tR4XN8b4zLVl/J4qMb0nf80Q4CXcpXDNJDY=
github.com/AzureAD/microsoft-authentication-library-for-go v0.5.3/go.mod h1:Vt9sXTKwMyGcOxSmLDMnGPgqsUg7m8pe215qMLrDXw4=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/aws/aws-sdk-go v1.44.52 h1:kHLbYJj59C7VrsLM4gm7pxsvaNIvhXCCIDYEFFoQ+VE=
github.com/aws/aws-sdk-go v1.44.52/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo=
github.com/aws/aws-sdk-go-v2 v1.16.7 h1:zfBwXus3u14OszRxGcqCDS4MfMCv10e8SMJ2r8Xm0Ns=
@@ -35,23 +35,35 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.16.9 h1:yOfILxyjmtr2ubRkRJldlHDFBhf5
github.com/aws/aws-sdk-go-v2/service/sts v1.16.9/go.mod h1:O1IvkYxr+39hRf960Us6j0x1P8pDqhTX+oXM5kQNl/Y=
github.com/aws/smithy-go v1.12.0 h1:gXpeZel/jPoWQ7OEmLIgCUnhkFftqNfwWUwAHSlp1v0=
github.com/aws/smithy-go v1.12.0/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA=
github.com/containerd/stargz-snapshotter/estargz v0.14.3 h1:OqlDCK3ZVUO6C3B/5FSkDwbkEETK84kQgEeFwDC+62k=
github.com/containerd/stargz-snapshotter/estargz v0.14.3/go.mod h1:KY//uOCIkSuNAHhJogcZtrNHdKrA99/FCCRjE3HD36o=
github.com/coreos/go-semver v0.3.0 h1:wkHLiw0WNATZnSG7epLsujiMCgPAc9xhjJ4tgnAxmfM=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dnaeon/go-vcr v1.1.0 h1:ReYa/UBrRyQdant9B4fNHGoCNKw6qh6P0fsdGmZpR7c=
github.com/dnaeon/go-vcr v1.1.0/go.mod h1:M7tiix8f0r6mKKJ3Yq/kqU1OYf3MnfmBWVbPx/yU9ko=
github.com/docker/cli v27.1.1+incompatible h1:goaZxOqs4QKxznZjjBWKONQci/MywhtRv2oNn0GkeZE=
github.com/docker/cli v27.1.1+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8=
github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docker/docker-credential-helpers v0.7.0 h1:xtCHsjxogADNZcdv1pKUHXryefjlVRqWqIhk/uXJp0A=
github.com/docker/docker-credential-helpers v0.7.0/go.mod h1:rETQfLdHNT3foU5kuNkFR1R1V12OJRRO5lzt2D1b5X0=
github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-jwt/jwt/v4 v4.2.0 h1:besgBTC8w8HjP6NzQdxwKH9Z5oQMZ24ThTrHp3cZ8eU=
github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-containerregistry v0.20.2 h1:B1wPJ1SN/S7pB+ZAimcciVD+r+yV/l/DSArMxlbwseo=
github.com/google/go-containerregistry v0.20.2/go.mod h1:z38EKdKh4h7IP2gSfUUqEvalZBqs6AoLeWfUy34nQC8=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
@@ -63,50 +75,79 @@ github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGw
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg=
github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI=
github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/montanaflynn/stats v0.6.6/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.0-rc3 h1:fzg1mXZFj8YdPeNkRXMg+zb88BFV0Ys52cJydRwBkb8=
github.com/opencontainers/image-spec v1.1.0-rc3/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8=
github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4/go.mod h1:N6UoU20jOqggOuDwUaBQpluzLNDqif3kq9z2wpdYEfQ=
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU=
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/urfave/cli v1.22.9 h1:cv3/KhXGBGjEXLC4bH0sLuJ9BewaAbpk5oyMOveu4pw=
github.com/urfave/cli v1.22.9/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa h1:zuSxTR4o9y82ebqCUJYNGJbGPo6sKVl54f/TVDObg1c=
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/urfave/cli v1.22.12 h1:igJgVw1JdKH+trcLWLeLwZjU9fEfPesQ+9/e4MQ44S8=
github.com/urfave/cli v1.22.12/go.mod h1:sSBEIC79qR6OvcmsD4U3KABeOTxDqQtdDnaFuUN30b8=
github.com/vbatts/tar-split v0.11.3 h1:hLFqsOLQ1SsppQNTMpkpPXClLDfC2A3Zgy9OUU+RVck=
github.com/vbatts/tar-split v0.11.3/go.mod h1:9QlHN18E+fEH7RdG+QAJJcuya3rqT7eXSTY7wGrAokY=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220725212005-46097bf591d3 h1:2yWTtPWWRcISTw3/o+s/Y4UOMnQL71DWyToOANFusCg=
golang.org/x/net v0.0.0-20220725212005-46097bf591d3/go.mod h1:AaygXjzTFtRAg2ttMY5RMuhpJ3cNnI0XpyFJD1iQRSM=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/sync v0.2.0 h1:PUR+T4wwASmuSTYdKjYHI5TD22Wy5ogLU5qZCOLxBrI=
golang.org/x/sync v0.2.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220906165534-d0df966e6959/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0=
gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8=
+283 -95
View File
@@ -5,41 +5,86 @@ import (
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/drone/drone-kaniko/pkg/artifact"
"github.com/drone/drone-kaniko/pkg/output"
"github.com/drone/drone-kaniko/pkg/tagger"
"github.com/google/go-containerregistry/pkg/crane"
"golang.org/x/mod/semver"
)
type (
// Build defines Docker build parameters.
Build struct {
DroneCommitRef string // Drone git commit reference
DroneRepoBranch string // Drone repo branch
Dockerfile string // Docker build Dockerfile
Context string // Docker build context
Tags []string // Docker build tags
AutoTag bool // Set this to auto detect tags from git commits and semver-tagged labels
AutoTagSuffix string // Suffix to append to the auto detect tags
ExpandTag bool // Set this to expand the `Tags` into semver-tagged labels
Args []string // Docker build args
Target string // Docker build target
Repo string // Docker build repository
Mirrors []string // Docker repository mirrors
Labels []string // Label map
SkipTlsVerify bool // Docker skip tls certificate verify for registry
SnapshotMode string // Kaniko snapshot mode
EnableCache bool // Whether to enable kaniko cache
CacheRepo string // Remote repository that will be used to store cached layers
CacheTTL int // Cache timeout in hours
DigestFile string // Digest file location
NoPush bool // Set this flag if you only want to build the image, without pushing to a registry
Verbosity string // Log level
Platform string // Allows to build with another default platform than the host, similarly to docker build --platform
SkipUnusedStages bool // Build only used stages
TarPath string // Set this flag to save the image as a tarball at path
Args []string // Docker build args
ArgsNew []string // docker build args with comma seperated values
AutoTag bool // Set this to auto detect tags from git commits and semver-tagged labels
AutoTagSuffix string // Suffix to append to the auto detect tags
CacheRepo string // Remote repository that will be used to store cached layers
CacheTTL int // Cache timeout in hours
Context string // Docker build context
DigestFile string // Digest file location
Dockerfile string // Docker build Dockerfile
DroneCommitRef string // Drone git commit reference
DroneRepoBranch string // Drone repo branch
EnableCache bool // Whether to enable kaniko cache
ExpandTag bool // Set this to expand the `Tags` into semver-tagged labels
IsMultipleBuildArgs bool // env variable for fallback for docker build args
Labels []string // Label map
Mirrors []string // Docker repository mirrors
NoPush bool // Set this flag if you only want to build the image, without pushing to a registry
Platform string // Allows to build with another default platform than the host, similarly to docker build --platform
PushOnly bool // Specify if the operation is push-only.
Repo string // Docker build repository
SkipTlsVerify bool // Docker skip tls certificate verify for registry
SkipUnusedStages bool // Build only used stages
SnapshotMode string // Kaniko snapshot mode
SourceTarPath string // Path to the local tarball to be pushed
Tags []string // Docker build tags
TarPath string // Set this flag to save the image as a tarball at path
Target string // Docker build target
Verbosity string // Log level
Cache bool // Enable or disable caching during the build process.
CacheDir string // Directory to store cached layers.
CacheCopyLayers bool // Enable or disable copying layers from the cache.
CacheRunLayers bool // Enable or disable running layers from the cache.
Cleanup bool // Enable or disable cleanup of temporary files.
CompressedCaching *bool // Enable or disable compressed caching.
ContextSubPath string // Sub-path within the context to build.
CustomPlatform string // Platform to use for building.
Force bool // Force building the image even if it already exists.
Git bool // Branch to clone if build context is a git repository .
ImageNameWithDigestFile string // Write image name with digest to a file.
ImageNameTagWithDigestFile string // Write image name with tag and digest to a file.
Insecure bool // Allow connecting to registries without TLS.
InsecurePull bool // Allow insecure pulls from the registry.
InsecureRegistry string // Use plain HTTP for registry communication.
Label string // Add metadata to an image.
LogFormat string // Set the log format for build output.
LogTimestamp bool // Show timestamps in build output.
OCILayoutPath string // Directory to store OCI layout.
PushRetry int // Number of times to retry pushing an image.
RegistryCertificate string // Path to a file containing a registry certificate.
RegistryClientCert string // Path to a file containing a registry client certificate.
RegistryMirror string // Mirror for registry pulls.
SkipDefaultRegistryFallback bool // Skip Docker Hub and default registry fallback.
Reproducible bool // Create a reproducible image.
SingleSnapshot bool // Only create a single snapshot of the image.
SkipTLSVerify bool // Skip TLS verification when connecting to the registry.
SkipPushPermissionCheck bool // Skip permission check when pushing.
SkipTLSVerifyPull bool // Skip TLS verification when pulling.
SkipTLSVerifyRegistry bool // Skip TLS verification when connecting to a registry.
UseNewRun bool // Use the new container runtime (`runc`) for builds.
IgnoreVarRun *bool // Ignore `/var/run` when copying from the context.
IgnorePath string // Ignore files matching the specified path pattern.
IgnorePaths []string // Ignore files matching the specified path pattern.
ImageFSExtractRetry int // Number of times to retry extracting the image filesystem.
ImageDownloadRetry int // Number of times to retry downloading layers.
}
// Artifact defines content of artifact file
@@ -61,12 +106,13 @@ type (
Build Build // Docker build configuration
Artifact Artifact // Artifact file content
Output Output // Output file content
// parameters for UTs to mock crane functionality
LoadImageFromTarball func(string) (v1.Image, error)
PushImageToRegistry func(v1.Image, string) error
}
)
// Excluded variables
var excludeList = []string{"PLUGIN_PIPELINE", "PLUGIN_USERNAME", "PLUGIN_PASSWORD", "PLUGIN_TAGS", "PLUGIN_REGISTRY", "PLUGIN_ARTIFACT_FILE", "PLUGIN_REPO", "PLUGIN_BUILD_ARGS"}
// labelsForTag returns the labels to use for the given tag, subject to the value of ExpandTag.
//
// Build information (e.g. +linux_amd64) is carried through to all labels.
@@ -134,10 +180,53 @@ func (b Build) AutoTags() (tags []string, err error) {
// Exec executes the plugin step
func (p Plugin) Exec() error {
if p.Build.NoPush && p.Build.PushOnly {
return fmt.Errorf("inputs no-push and push-only cannot be used together. please define only one")
}
if !p.Build.NoPush && p.Build.Repo == "" {
return fmt.Errorf("repository name to publish image must be specified")
}
if p.Build.PushOnly {
// When push-only is set, source_tar_path MUST be provided
if p.Build.SourceTarPath == "" {
return fmt.Errorf("source_tar_path is required when push_only is set. please provide a valid tarball path")
}
if _, err := os.Stat(p.Build.SourceTarPath); os.IsNotExist(err) {
return fmt.Errorf("image tarball does not exist at path: %s", p.Build.SourceTarPath)
}
if p.Build.Repo == "" {
return fmt.Errorf("missing required destination repository for push-only operation")
}
// Load the image from the tarball
img, err := crane.Load(p.Build.SourceTarPath)
if err != nil {
return fmt.Errorf("failed to load image from tarball: %v", err)
}
// If no tags are specified, use 'latest'
tags := p.Build.Tags
for _, tag := range tags {
dest := fmt.Sprintf("%s:%s", p.Build.Repo, tag)
// Push the image to the destination
err := crane.Push(img, dest)
if err != nil {
return fmt.Errorf("failed to push image from tarball [%s] to destination [%s]: %v", p.Build.SourceTarPath, dest, err)
}
fmt.Printf("Successfully pushed image - '%s'\n to %s\n", dest, p.Build.Repo)
}
return nil
}
if _, err := os.Stat(p.Build.Dockerfile); os.IsNotExist(err) {
return fmt.Errorf("dockerfile does not exist at path: %s", p.Build.Dockerfile)
}
@@ -169,8 +258,14 @@ func (p Plugin) Exec() error {
}
// Set the build arguments
for _, arg := range p.Build.Args {
cmdArgs = append(cmdArgs, fmt.Sprintf("--build-arg=%s", arg))
if p.Build.IsMultipleBuildArgs {
for _, arg := range p.Build.ArgsNew {
cmdArgs = append(cmdArgs, "--build-arg", arg)
}
} else {
for _, arg := range p.Build.Args {
cmdArgs = append(cmdArgs, "--build-arg", arg)
}
}
// Set the labels
for _, label := range p.Build.Labels {
@@ -189,7 +284,7 @@ func (p Plugin) Exec() error {
}
if p.Build.SnapshotMode != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--snapshotMode=%s", p.Build.SnapshotMode))
cmdArgs = append(cmdArgs, fmt.Sprintf("--snapshot-mode=%s", p.Build.SnapshotMode))
}
if p.Build.EnableCache {
@@ -225,13 +320,151 @@ func (p Plugin) Exec() error {
}
if p.Build.TarPath != "" {
tarDir := filepath.Dir(p.Build.TarPath)
if _, err := os.Stat(tarDir); os.IsNotExist(err) {
if mkdirErr := os.MkdirAll(tarDir, 0755); mkdirErr != nil {
return fmt.Errorf("failed to create directory for tar path %s: %v", tarDir, mkdirErr)
}
}
cmdArgs = append(cmdArgs, fmt.Sprintf("--tar-path=%s", p.Build.TarPath))
}
//Read all PLUGIN_ env vars
//parse them such that PLUGIN_ENV_ARG is set to the value of --env-arg
//Add the value of --env-arg to cmdArgs if it does not exist
cmdArgs = getPluginEnvVars(cmdArgs)
if p.Build.CacheCopyLayers {
cmdArgs = append(cmdArgs, "--cache-copy-layers")
}
if p.Build.CacheRunLayers {
cmdArgs = append(cmdArgs, "--cache-run-layers=true")
}
if p.Build.Cleanup {
cmdArgs = append(cmdArgs, "--cleanup=true")
}
if p.Build.CompressedCaching != nil {
if *p.Build.CompressedCaching {
cmdArgs = append(cmdArgs, "--compressed-caching=true")
} else {
cmdArgs = append(cmdArgs, "--compressed-caching=false")
}
}
if p.Build.ContextSubPath != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--context-sub-path=%s", p.Build.ContextSubPath))
}
if p.Build.CustomPlatform != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--custom-platform=%s", p.Build.CustomPlatform))
}
if p.Build.Force {
cmdArgs = append(cmdArgs, "--force")
}
if p.Build.Git {
cmdArgs = append(cmdArgs, "--git")
}
if p.Build.ImageNameWithDigestFile != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--image-name-with-digest-file=%s", p.Build.ImageNameWithDigestFile))
}
if p.Build.ImageNameTagWithDigestFile != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--image-name-tag-with-digest-file=%s", p.Build.ImageNameTagWithDigestFile))
}
if p.Build.Insecure {
cmdArgs = append(cmdArgs, "--insecure")
}
if p.Build.InsecurePull {
cmdArgs = append(cmdArgs, "--insecure-pull")
}
if p.Build.InsecureRegistry != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--insecure-registry=%s", p.Build.InsecureRegistry))
}
if p.Build.LogFormat != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--log-format=%s", p.Build.LogFormat))
}
if p.Build.LogTimestamp {
cmdArgs = append(cmdArgs, "--log-timestamp")
}
if p.Build.OCILayoutPath != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--oci-layout-path=%s", p.Build.OCILayoutPath))
}
if p.Build.PushRetry != 0 {
cmdArgs = append(cmdArgs, fmt.Sprintf("--push-retry=%d", p.Build.PushRetry))
}
if p.Build.RegistryCertificate != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--registry-certificate=%s", p.Build.RegistryCertificate))
}
if p.Build.RegistryClientCert != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--registry-client-cert=%s", p.Build.RegistryClientCert))
}
if p.Build.SkipDefaultRegistryFallback {
cmdArgs = append(cmdArgs, "--skip-default-registry-fallback")
}
if p.Build.Reproducible {
cmdArgs = append(cmdArgs, "--reproducible")
}
if p.Build.SingleSnapshot {
cmdArgs = append(cmdArgs, "--single-snapshot")
}
if p.Build.SkipPushPermissionCheck {
cmdArgs = append(cmdArgs, "--skip-push-permission-check")
}
if p.Build.SkipTLSVerifyPull {
cmdArgs = append(cmdArgs, "--skip-tls-verify-pull")
}
if p.Build.SkipTLSVerifyRegistry {
cmdArgs = append(cmdArgs, "--skip-tls-verify-registry")
}
if p.Build.UseNewRun {
cmdArgs = append(cmdArgs, "--use-new-run")
}
if p.Build.IgnoreVarRun != nil {
if *p.Build.IgnoreVarRun {
cmdArgs = append(cmdArgs, "--ignore-var-run=true")
} else {
cmdArgs = append(cmdArgs, "--ignore-var-run=false")
}
}
if p.Build.IgnorePath != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--ignore-path=%s", p.Build.IgnorePath))
}
if p.Build.IgnorePaths != nil {
for _, path := range p.Build.IgnorePaths {
trimmed := strings.TrimSpace(path)
if trimmed != "" {
cmdArgs = append(cmdArgs, fmt.Sprintf("--ignore-path=%s", trimmed))
}
}
}
if p.Build.ImageFSExtractRetry != 0 {
cmdArgs = append(cmdArgs, fmt.Sprintf("--image-fs-extract-retry=%d", p.Build.ImageFSExtractRetry))
}
if p.Build.ImageDownloadRetry != 0 {
cmdArgs = append(cmdArgs, fmt.Sprintf("--image-download-retry=%d", p.Build.ImageDownloadRetry))
}
cmd := exec.Command("/kaniko/executor", cmdArgs...)
cmd.Stdout = os.Stdout
@@ -250,15 +483,27 @@ func (p Plugin) Exec() error {
}
}
if p.Output.OutputFile != "" {
if err = output.WritePluginOutputFile(p.Output.OutputFile, getDigest(p.Build.DigestFile)); err != nil {
fmt.Fprintf(os.Stderr, "failed to write plugin output file at path: %s with error: %s\n", p.Output.OutputFile, err)
}
p.Output.OutputFile = os.Getenv("DRONE_OUTPUT")
var tarPath string
if p.Build.TarPath != "" {
tarPath = getTarPath(p.Build.TarPath)
}
if err = output.WritePluginOutputFile(p.Output.OutputFile, getDigest(p.Build.DigestFile), tarPath); err != nil {
fmt.Fprintf(os.Stderr, "failed to write plugin output file at path: %s with error: %s\n", p.Output.OutputFile, err)
}
return nil
}
func getTarPath(tarPath string) string {
tarDir := filepath.Dir(tarPath)
if _, err := os.Stat(tarDir); err != nil && os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, "Warning: tar path does not exist: %s\n", tarPath)
return ""
}
return tarPath
}
func getDigest(digestFile string) string {
content, err := ioutil.ReadFile(digestFile)
if err != nil {
@@ -272,60 +517,3 @@ func getDigest(digestFile string) string {
func trace(cmd *exec.Cmd) {
fmt.Fprintf(os.Stdout, "+ %s\n", strings.Join(cmd.Args, " "))
}
func getPluginEnvVars(cmdArgs []string) []string {
envVars := os.Environ()
// Iterate through environment variables
for _, envVar := range envVars {
// Check if the variable starts with PLUGIN_
if strings.HasPrefix(envVar, "PLUGIN_") && !contains(excludeList, envVar) {
// Split the variable into key and value
parts := strings.SplitN(envVar, "=", 2)
if len(parts) != 2 {
continue
}
key := parts[0]
value := parts[1]
// Trim the "PLUGIN_" prefix
flagName := strings.TrimPrefix(key, "PLUGIN_")
// Replace underscores with hyphens and convert to lowercase
flagName = strings.ReplaceAll(flagName, "_", "-")
flagName = strings.ToLower(flagName)
// Format the flag name with "--" prefix
flag := "--" + flagName
// Check if the flag already exists in cmdArgs
exists := false
for _, arg := range cmdArgs {
if strings.HasPrefix(arg, flag) {
exists = true
break
}
}
// If the flag does not exist, add it to cmdArgs
if !exists {
if value == "" {
cmdArgs = append(cmdArgs, flag)
} else {
cmdArgs = append(cmdArgs, fmt.Sprintf("%s=%s", flag, value))
}
}
}
}
return cmdArgs
}
// Function to check if a string is in a slice
func contains(slice []string, str string) bool {
for _, s := range slice {
if strings.HasPrefix(str, s) {
return true
}
}
return false
}
+304
View File
@@ -1,6 +1,10 @@
package kaniko
import (
"archive/tar"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/google/go-cmp/cmp"
@@ -148,3 +152,303 @@ func TestBuild_AutoTags(t *testing.T) {
}
})
}
func TestTarPathValidation(t *testing.T) {
tests := []struct {
name string
tarPath string
setup func(string) error
cleanup func(string) error
expectSuccess bool
privileged bool
}{
{
name: "valid_path_privileged",
tarPath: "",
setup: func(path string) error {
tmpDir, err := os.MkdirTemp("", "test-image-tar")
if err != nil {
return err
}
os.Setenv("DRONE_WORKSPACE", tmpDir)
return nil
},
cleanup: func(path string) error {
tmpDir := os.Getenv("DRONE_WORKSPACE")
os.Unsetenv("DRONE_WORKSPACE")
return os.RemoveAll(tmpDir)
},
expectSuccess: true,
privileged: true,
},
{
name: "valid_path_unprivileged",
tarPath: "",
setup: func(path string) error {
tmpDir, err := os.MkdirTemp("", "test-image-tar")
if err != nil {
return err
}
os.Setenv("DRONE_WORKSPACE", tmpDir)
return nil
},
cleanup: func(path string) error {
tmpDir := os.Getenv("DRONE_WORKSPACE")
os.Unsetenv("DRONE_WORKSPACE")
return os.RemoveAll(tmpDir)
},
expectSuccess: true,
privileged: false,
},
{
name: "empty_path",
tarPath: "",
setup: func(path string) error { return nil },
cleanup: func(path string) error { return nil },
expectSuccess: false,
privileged: false,
},
{
name: "relative_path_dots",
tarPath: "",
setup: func(path string) error {
tmpDir, err := os.MkdirTemp("", "test-image-tar")
if err != nil {
return err
}
os.Setenv("DRONE_WORKSPACE", tmpDir)
return nil
},
cleanup: func(path string) error {
tmpDir := os.Getenv("DRONE_WORKSPACE")
os.Unsetenv("DRONE_WORKSPACE")
return os.RemoveAll(tmpDir)
},
expectSuccess: true,
privileged: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Skip privileged tests if not running as root
if tt.privileged && os.Getuid() != 0 {
t.Skip("Skipping privileged test as not running as root")
}
if err := tt.setup(tt.tarPath); err != nil {
t.Fatalf("Setup failed: %v", err)
}
defer tt.cleanup(tt.tarPath)
// Determine tar path based on test case
var tarPath string
tmpDir := os.Getenv("DRONE_WORKSPACE")
switch tt.name {
case "valid_path_privileged", "valid_path_unprivileged":
tarPath = filepath.Join(tmpDir, "test", "image.tar")
case "invalid_path_no_permissions":
tarPath = "/test/image.tar"
case "relative_path_dots":
tarPath = filepath.Join("..", "test", "image.tar")
default:
tarPath = tt.tarPath
}
p := Plugin{
Build: Build{
TarPath: tarPath,
},
}
tarDir := filepath.Dir(p.Build.TarPath)
err := os.MkdirAll(tarDir, 0755)
if tt.expectSuccess {
if err != nil {
t.Errorf("Expected directory creation to succeed, got error: %v", err)
}
if _, err := os.Stat(tarDir); err != nil {
t.Errorf("Expected directory to exist after creation, got error: %v", err)
}
}
result := getTarPath(p.Build.TarPath)
if tt.expectSuccess && result == "" {
t.Error("Expected non-empty tar path, got empty string")
}
if !tt.expectSuccess && result != "" {
t.Error("Expected empty tar path, got non-empty string")
}
})
}
}
func TestSourceTarballPush(t *testing.T) {
tests := []struct {
name string
sourceTarPath string
repo string
autoTag bool
tags []string
commitRef string
repoBranch string
expectedError bool
expectedTags []string
mockLoadErr error
mockPushErr error
}{
{
name: "empty_repo_fails",
sourceTarPath: "/path/to/image.tar",
repo: "",
expectedError: true,
},
{
name: "nonexistent_tarball_fails",
sourceTarPath: "/path/that/does/not/exist/image.tar",
repo: "test-repo",
expectedError: true,
},
{
name: "load_image_fails",
sourceTarPath: createTestTarball(t),
repo: "test-repo",
expectedError: true,
mockLoadErr: fmt.Errorf("load failed"),
},
{
name: "push_image_fails",
sourceTarPath: createTestTarball(t),
repo: "test-repo",
expectedError: true,
expectedTags: []string{"latest"},
mockPushErr: fmt.Errorf("push failed"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockPlugin := Plugin{
Build: Build{
SourceTarPath: tt.sourceTarPath,
Repo: tt.repo,
Tags: tt.tags,
AutoTag: tt.autoTag,
DroneCommitRef: tt.commitRef,
DroneRepoBranch: tt.repoBranch,
},
LoadImageFromTarball: MockCraneLoad(tt.sourceTarPath, tt.mockLoadErr),
PushImageToRegistry: MockCranePush(tt.mockPushErr),
}
err := mockPlugin.Exec()
if tt.expectedError {
if err == nil {
t.Errorf("Expected an error, but got none")
}
} else {
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
})
}
}
// Helper function to create a test tarball
func createTestTarball(t *testing.T) string {
// Create a temporary directory for the tarball contents
tmpDir, err := os.MkdirTemp("", "test-tarball-*")
if err != nil {
t.Fatalf("Failed to create temp directory: %v", err)
}
defer os.RemoveAll(tmpDir)
// Create a minimal `manifest.json` file with a valid hash
manifestPath := filepath.Join(tmpDir, "manifest.json")
manifestContent := `[{
"Config": "config.json",
"RepoTags": ["test-repo:latest"],
"Layers": ["layer.tar"]
}]`
err = os.WriteFile(manifestPath, []byte(manifestContent), 0644)
if err != nil {
t.Fatalf("Failed to create manifest.json: %v", err)
}
// Create a valid `config.json` file with a dummy hash
configPath := filepath.Join(tmpDir, "config.json")
configContent := `{
"architecture": "amd64",
"os": "linux",
"rootfs": {
"type": "layers",
"diff_ids": ["sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]
}
}`
err = os.WriteFile(configPath, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create config.json: %v", err)
}
// Create a dummy `layer.tar` file
layerPath := filepath.Join(tmpDir, "layer.tar")
layerFile, err := os.Create(layerPath)
if err != nil {
t.Fatalf("Failed to create layer.tar: %v", err)
}
defer layerFile.Close()
_, err = layerFile.Write([]byte("dummy layer content"))
if err != nil {
t.Fatalf("Failed to write to layer.tar: %v", err)
}
// Create a tarball from the temp directory
tarballPath := filepath.Join(os.TempDir(), "test-image.tar")
tarballFile, err := os.Create(tarballPath)
if err != nil {
t.Fatalf("Failed to create tarball: %v", err)
}
defer tarballFile.Close()
tw := tar.NewWriter(tarballFile)
defer tw.Close()
err = filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relPath, _ := filepath.Rel(tmpDir, path)
if relPath == "." {
return nil
}
header, err := tar.FileInfoHeader(info, path)
if err != nil {
return err
}
header.Name = relPath
if err := tw.WriteHeader(header); err != nil {
return err
}
if !info.IsDir() {
fileContent, err := os.ReadFile(path)
if err != nil {
return err
}
_, err = tw.Write(fileContent)
if err != nil {
return err
}
}
return nil
})
if err != nil {
t.Fatalf("Failed to write tarball: %v", err)
}
return tarballPath
}
+71
View File
@@ -0,0 +1,71 @@
package kaniko
import (
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/types"
)
func MockCraneLoad(path string, loadErr error) func(string) (v1.Image, error) {
return func(inputPath string) (v1.Image, error) {
if loadErr != nil {
return nil, loadErr
}
return &mockImage{}, nil
}
}
func MockCranePush(pushErr error) func(v1.Image, string) error {
return func(img v1.Image, dest string) error {
if pushErr != nil {
return pushErr
}
return nil
}
}
// mockImage is a mock implementation of v1.Image interface
type mockImage struct{}
func (m *mockImage) Size() (int64, error) {
return 0, nil
}
func (m *mockImage) RawConfigFile() ([]byte, error) {
return nil, nil
}
func (m *mockImage) Digest() (v1.Hash, error) {
return v1.Hash{}, nil
}
func (m *mockImage) Manifest() (*v1.Manifest, error) {
return nil, nil
}
func (m *mockImage) RawManifest() ([]byte, error) {
return nil, nil
}
func (m *mockImage) LayerByDigest(hash v1.Hash) (v1.Layer, error) {
return nil, nil
}
func (m *mockImage) LayerByDiffID(hash v1.Hash) (v1.Layer, error) {
return nil, nil
}
func (m *mockImage) Layers() ([]v1.Layer, error) {
return nil, nil
}
func (m *mockImage) MediaType() (types.MediaType, error) {
return "", nil
}
func (m *mockImage) ConfigFile() (*v1.ConfigFile, error) {
return nil, nil
}
func (m *mockImage) ConfigName() (v1.Hash, error) {
return v1.Hash{}, nil
}
+67 -4
View File
@@ -2,7 +2,18 @@ package docker
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/pkg/errors"
)
const (
v2HubRegistryURL string = "https://registry.hub.docker.com/v2/"
v1RegistryURL string = "https://index.docker.io/v1/" // Default registry
v2RegistryURL string = "https://index.docker.io/v2/" // v2 registry is not supported
)
type (
@@ -12,19 +23,25 @@ type (
Config struct {
Auths map[string]Auth `json:"auths"`
CredHelpers map[string]string `json:"credHelpers"`
CredHelpers map[string]string `json:"credHelpers,omitempty"`
}
)
type RegistryCredentials struct {
Registry string
Username string
Password string
}
func NewConfig() *Config {
return &Config{
Auths: map[string]Auth{},
CredHelpers: map[string]string{},
Auths: make(map[string]Auth),
CredHelpers: make(map[string]string),
}
}
func (c *Config) SetAuth(registry, username, password string) {
authBytes := []byte(fmt.Sprintf("%s:%s", username, password))
authBytes := []byte(username + ":" + password)
encodedString := base64.StdEncoding.EncodeToString(authBytes)
c.Auths[registry] = Auth{Auth: encodedString}
}
@@ -32,3 +49,49 @@ func (c *Config) SetAuth(registry, username, password string) {
func (c *Config) SetCredHelper(registry, helper string) {
c.CredHelpers[registry] = helper
}
func (c *Config) CreateDockerConfig(credentials []RegistryCredentials, dockerPath string) error {
for _, cred := range credentials {
if cred.Registry != "" {
// update v2 docker registry to v1
if cred.Registry == v2RegistryURL || cred.Registry == v2HubRegistryURL {
fmt.Printf("Docker v2 registry '%s' is not supported in kaniko. Refer issue: https://github.com/GoogleContainerTools/kaniko/issues/1209\n", cred.Registry)
fmt.Printf("Using v1 registry instead: %s\n", v1RegistryURL)
cred.Registry = v1RegistryURL
}
if cred.Username == "" {
return fmt.Errorf("Username must be specified for registry: %s", cred.Registry)
}
if cred.Password == "" {
return fmt.Errorf("Password must be specified for registry: %s", cred.Registry)
}
c.SetAuth(cred.Registry, cred.Username, cred.Password)
}
}
jsonBytes, err := json.Marshal(c)
if err != nil {
return errors.Wrap(err, "failed to serialize docker config json")
}
if err := WriteDockerConfig(jsonBytes, dockerPath); err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to write docker config to path: %s", dockerPath))
}
return nil
}
func WriteDockerConfig(data []byte, path string) (string error) {
err := os.MkdirAll(path, 0600)
if err != nil {
if !os.IsExist(err) {
return errors.Wrap(err, fmt.Sprintf("failed to create %s directory", path))
}
}
filePath := path + "/config.json"
err = ioutil.WriteFile(filePath, data, 0644)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to create docker config file at %s", path))
}
return nil
}
+38 -8
View File
@@ -2,24 +2,54 @@ package docker
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
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])
bytes, err := json.Marshal(c)
if err != nil {
t.Error("json marshal failed")
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",
},
}
want := `{"auths":{"https://index.docker.io/v1/":{"auth":"dGVzdDpwYXNzd29yZA=="}},"credHelpers":{"public.ecr.aws":"ecr-login"}}`
got := string(bytes)
err = c.CreateDockerConfig(credentials, tempDir)
assert.NoError(t, err)
if want != got {
t.Errorf("unexpected json output:\n want: %s\n got: %s", want, got)
}
configPath := filepath.Join(tempDir, "config.json")
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)
}
-35
View File
@@ -1,35 +0,0 @@
package docker
import (
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"github.com/pkg/errors"
)
// Create the docker config file for authentication
func CreateDockerCfgFile(username, password, registry, path string) error {
if username == "" {
return fmt.Errorf("Username must be specified")
}
if password == "" {
return fmt.Errorf("Password must be specified")
}
err := os.MkdirAll(path, 0600)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to create %s directory", path))
}
authBytes := []byte(fmt.Sprintf("%s:%s", username, password))
encodedString := base64.StdEncoding.EncodeToString(authBytes)
jsonBytes := []byte(fmt.Sprintf(`{"auths": {"%s": {"auth": "%s"}}}`, "https://"+registry, encodedString))
filePath := path + "/config.json"
err = ioutil.WriteFile(filePath, jsonBytes, 0644)
if err != nil {
return errors.Wrap(err, "failed to create docker config file")
}
return nil
}
+9 -3
View File
@@ -4,9 +4,15 @@ import (
"github.com/joho/godotenv"
)
func WritePluginOutputFile(outputFilePath, digest string) error {
output := map[string]string{
"digest": digest,
func WritePluginOutputFile(outputFilePath, digest string, pluginTarPath string) error {
output := make(map[string]string)
if digest != "" {
output["digest"] = digest
}
if pluginTarPath != "" {
output["IMAGE_TAR_PATH"] = pluginTarPath
}
return godotenv.Write(output, outputFilePath)
}
+145
View File
@@ -0,0 +1,145 @@
package output
import (
"os"
"path/filepath"
"testing"
)
func TestWritePluginOutputFile(t *testing.T) {
tests := []struct {
name string
outputPath string
digest string
tarPath string
setup func(string) error
cleanup func(string) error
expectError bool
privileged bool
}{
{
name: "valid_output_privileged",
outputPath: "",
digest: "sha256:test",
tarPath: "",
setup: func(path string) error {
tmpDir, err := os.MkdirTemp("", "test-output")
if err != nil {
return err
}
os.Setenv("DRONE_WORKSPACE", tmpDir)
return nil
},
cleanup: func(path string) error {
tmpDir := os.Getenv("DRONE_WORKSPACE")
os.Unsetenv("DRONE_WORKSPACE")
return os.RemoveAll(tmpDir)
},
expectError: false,
privileged: true,
},
{
name: "valid_output_unprivileged",
outputPath: "",
digest: "sha256:test",
tarPath: "",
setup: func(path string) error {
tmpDir, err := os.MkdirTemp("", "test-output")
if err != nil {
return err
}
os.Setenv("DRONE_WORKSPACE", tmpDir)
return nil
},
cleanup: func(path string) error {
tmpDir := os.Getenv("DRONE_WORKSPACE")
os.Unsetenv("DRONE_WORKSPACE")
return os.RemoveAll(tmpDir)
},
expectError: false,
privileged: false,
},
{
name: "digest_only",
outputPath: "",
digest: "sha256:test",
tarPath: "",
setup: func(path string) error {
tmpDir, err := os.MkdirTemp("", "test-output")
if err != nil {
return err
}
os.Setenv("DRONE_WORKSPACE", tmpDir)
return nil
},
cleanup: func(path string) error {
tmpDir := os.Getenv("DRONE_WORKSPACE")
os.Unsetenv("DRONE_WORKSPACE")
return os.RemoveAll(tmpDir)
},
expectError: false,
privileged: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Skip privileged tests if not running as root
if tt.privileged && os.Getuid() != 0 {
t.Skip("Skipping privileged test as not running as root")
}
if err := tt.setup(tt.outputPath); err != nil {
t.Fatalf("Setup failed: %v", err)
}
defer tt.cleanup(tt.outputPath)
tmpDir := os.Getenv("DRONE_WORKSPACE")
var outputPath, tarPath string
switch tt.name {
case "valid_output_privileged", "valid_output_unprivileged":
outputPath = filepath.Join(tmpDir, "test", "output.env")
tarPath = filepath.Join(tmpDir, "test", "image.tar")
case "invalid_output_path":
outputPath = filepath.Join("/root", "test", "output.env")
tarPath = filepath.Join("/root", "test", "image.tar")
case "digest_only":
outputPath = filepath.Join(tmpDir, "test", "output.env")
tarPath = ""
}
err := os.MkdirAll(filepath.Dir(outputPath), 0755)
if err != nil {
t.Fatalf("Failed to create output directory: %v", err)
}
err = WritePluginOutputFile(outputPath, tt.digest, tarPath)
if tt.expectError && err == nil {
t.Error("Expected error, got none")
}
if !tt.expectError && err != nil {
t.Errorf("Expected no error, got: %v", err)
}
if !tt.expectError && err == nil {
content, err := os.ReadFile(outputPath)
if err != nil {
t.Fatalf("Failed to read output file: %v", err)
}
if tt.digest != "" && !contains(string(content), tt.digest) {
t.Error("Expected digest in output file")
}
if tarPath != "" && !contains(string(content), tarPath) {
t.Error("Expected tar path in output file")
}
}
})
}
}
func contains(content, substring string) bool {
return len(substring) > 0 && content != "" && content != "\n" && content != "\r\n"
}