-
Notifications
You must be signed in to change notification settings - Fork 56
/
main.go
698 lines (653 loc) · 21.3 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
package main
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
kaniko "github.com/drone/drone-kaniko"
"github.com/drone/drone-kaniko/pkg/artifact"
"github.com/drone/drone-kaniko/pkg/docker"
)
const (
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"
defaultDigestFile string = "/kaniko/digest-file"
finalUrl string = "https://portal.azure.com/#view/Microsoft_Azure_ContainerRegistries/TagMetadataBlade/registryId/"
)
var (
ACRCertPath = "/kaniko/acr-cert.pem"
pluginVersion = "unknown"
username = "00000000-0000-0000-0000-000000000000"
maxPageCount = 1000 // maximum count of pages to cycle through before we break out
)
func main() {
// TODO Add the env file functionality
app := cli.NewApp()
app.Name = "kaniko docker plugin"
app.Usage = "kaniko docker plugin"
app.Action = run
app.Version = pluginVersion
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "dockerfile",
Usage: "build dockerfile",
Value: "Dockerfile",
EnvVar: "PLUGIN_DOCKERFILE",
},
cli.StringFlag{
Name: "context",
Usage: "build context",
Value: ".",
EnvVar: "PLUGIN_CONTEXT",
},
cli.StringFlag{
Name: "drone-commit-ref",
Usage: "git commit ref passed by Drone",
EnvVar: "DRONE_COMMIT_REF",
},
cli.StringFlag{
Name: "drone-repo-branch",
Usage: "git repository default branch passed by Drone",
EnvVar: "DRONE_REPO_BRANCH",
},
cli.StringSliceFlag{
Name: "tags",
Usage: "build tags",
Value: &cli.StringSlice{"latest"},
EnvVar: "PLUGIN_TAGS",
FilePath: ".tags",
},
cli.BoolFlag{
Name: "expand-tag",
Usage: "enable for semver tagging",
EnvVar: "PLUGIN_EXPAND_TAG",
},
cli.BoolFlag{
Name: "auto-tag",
Usage: "enable auto generation of build tags",
EnvVar: "PLUGIN_AUTO_TAG",
},
cli.StringFlag{
Name: "auto-tag-suffix",
Usage: "the suffix of auto build tags",
EnvVar: "PLUGIN_AUTO_TAG_SUFFIX",
},
cli.StringSliceFlag{
Name: "args",
Usage: "build args",
EnvVar: "PLUGIN_BUILD_ARGS",
},
cli.StringFlag{
Name: "target",
Usage: "build target",
EnvVar: "PLUGIN_TARGET",
},
cli.StringFlag{
Name: "repo",
Usage: "docker repository",
EnvVar: "PLUGIN_REPO",
},
cli.BoolFlag{
Name: "create-repository",
Usage: "create ACR repository",
EnvVar: "PLUGIN_CREATE_REPOSITORY",
},
cli.StringSliceFlag{
Name: "custom-labels",
Usage: "additional k=v labels",
EnvVar: "PLUGIN_CUSTOM_LABELS",
},
cli.StringFlag{
Name: "registry",
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",
EnvVar: "PLUGIN_REGISTRY_MIRRORS",
},
cli.StringFlag{
Name: "client-secret",
Usage: "Azure client secret",
EnvVar: "CLIENT_SECRET",
},
cli.StringFlag{
Name: "client-cert",
Usage: "Azure client certificate encoded in base64 format",
EnvVar: "CLIENT_CERTIFICATE",
},
cli.StringFlag{
Name: "tenant-id",
Usage: "Azure Tenant Id",
EnvVar: "TENANT_ID",
},
cli.StringFlag{
Name: "subscription-id",
Usage: "Azure Subscription Id",
EnvVar: "SUBSCRIPTION_ID",
},
cli.StringFlag{
Name: "client-id",
Usage: "Azure Client Id",
EnvVar: "CLIENT_ID",
},
cli.StringFlag{
Name: "snapshot-mode",
Usage: "Specify one of full, redo or time as snapshot mode",
EnvVar: "PLUGIN_SNAPSHOT_MODE",
},
cli.StringFlag{
Name: "lifecycle-policy",
Usage: "Path to lifecycle policy file",
EnvVar: "PLUGIN_LIFECYCLE_POLICY",
},
cli.StringFlag{
Name: "repository-policy",
Usage: "Path to repository policy file",
EnvVar: "PLUGIN_REPOSITORY_POLICY",
},
cli.BoolFlag{
Name: "enable-cache",
Usage: "Set this flag to opt into caching with kaniko",
EnvVar: "PLUGIN_ENABLE_CACHE",
},
cli.StringFlag{
Name: "cache-repo",
Usage: "Remote repository that will be used to store cached layers. Cache repo should be present in specified registry. enable-cache needs to be set to use this flag",
EnvVar: "PLUGIN_CACHE_REPO",
},
cli.IntFlag{
Name: "cache-ttl",
Usage: "Cache timeout in hours. Defaults to two weeks.",
EnvVar: "PLUGIN_CACHE_TTL",
},
cli.StringFlag{
Name: "artifact-file",
Usage: "Artifact file location that will be generated by the plugin. This file will include information of docker images that are uploaded by the plugin.",
EnvVar: "PLUGIN_ARTIFACT_FILE",
},
cli.BoolFlag{
Name: "no-push",
Usage: "Set this flag if you only want to build the image, without pushing to a registry",
EnvVar: "PLUGIN_NO_PUSH",
},
cli.StringFlag{
Name: "verbosity",
Usage: "Set this flag with value as oneof <panic|fatal|error|warn|info|debug|trace> to set the logging level for kaniko. Defaults to info.",
EnvVar: "PLUGIN_VERBOSITY",
},
cli.StringFlag{
Name: "platform",
Usage: "Allows to build with another default platform than the host, similarly to docker build --platform",
EnvVar: "PLUGIN_PLATFORM",
},
cli.BoolFlag{
Name: "skip-unused-stages",
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 {
logrus.Fatal(err)
}
}
func run(c *cli.Context) error {
registry := c.String("registry")
noPush := c.Bool("no-push")
publicUrl, err := setupAuth(
c.String("tenant-id"),
c.String("client-id"),
c.String("client-cert"),
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 {
return err
}
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"),
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"),
ImageFSExtractRetry: c.Int("image-fs-extract-retry"),
ImageDownloadRetry: c.Int("image-download-retry"),
},
Artifact: kaniko.Artifact{
Tags: c.StringSlice("tags"),
Repo: c.String("repo"),
Registry: publicUrl, // this is public url on which the artifact can be seen
ArtifactFile: c.String("artifact-file"),
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, dockerUsername, dockerPassword, dockerRegistry string, noPush bool) (string, error) {
if registry == "" {
return "", fmt.Errorf("registry must be specified")
}
if noPush {
return "", nil
}
// case of client secret or cert based auth
if clientId != "" {
// only setup auth when pushing or credentials are defined
token, publicUrl, err := getACRToken(subscriptionId, tenantId, clientId, clientSecret, cert, registry)
if err != nil {
return "", errors.Wrap(err, "failed to fetch ACR Token")
}
// 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
} else {
return "", fmt.Errorf("managed authentication is not supported")
}
}
func getACRToken(subscriptionId, tenantId, clientId, clientSecret, cert, registry string) (string, string, error) {
if tenantId == "" {
return "", "", fmt.Errorf("tenantId can't be empty for AAD authentication")
}
if clientId == "" {
return "", "", fmt.Errorf("clientId can't be empty for AAD authentication")
}
if clientSecret == "" && cert == "" {
return "", "", fmt.Errorf("one of client secret or cert should be defined")
}
// in case of authentication via cert
if cert != "" {
err := setupACRCert(cert)
if err != nil {
errors.Wrap(err, "failed to push setup cert file")
}
}
if err := os.Setenv(clientIdEnv, clientId); err != nil {
return "", "", errors.Wrap(err, "failed to set env variable client Id")
}
if err := os.Setenv(clientSecretKeyEnv, clientSecret); err != nil {
return "", "", errors.Wrap(err, "failed to set env variable client secret")
}
if err := os.Setenv(tenantKeyEnv, tenantId); err != nil {
return "", "", errors.Wrap(err, "failed to set env variable tenant Id")
}
if err := os.Setenv(certPathEnv, ACRCertPath); err != nil {
return "", "", errors.Wrap(err, "failed to set env variable cert path")
}
env, err := azidentity.NewEnvironmentCredential(nil)
if err != nil {
return "", "", errors.Wrap(err, "failed to get env credentials from azure")
}
policy := policy.TokenRequestOptions{
Scopes: []string{"https://management.azure.com/.default"},
}
os.Unsetenv(clientIdEnv)
os.Unsetenv(clientSecretKeyEnv)
os.Unsetenv(tenantKeyEnv)
os.Unsetenv(certPathEnv)
azToken, err := env.GetToken(context.Background(), policy)
if err != nil {
return "", "", errors.Wrap(err, "failed to fetch access token")
}
publicUrl, err := getPublicUrl(azToken.Token, registry, subscriptionId)
if err != nil {
// execution should not fail because of this error.
fmt.Fprintf(os.Stderr, "failed to get public url with error: %s\n", err)
}
ACRToken, err := fetchACRToken(tenantId, azToken.Token, registry)
if err != nil {
return "", "", errors.Wrap(err, "failed to fetch ACR token")
}
return ACRToken, publicUrl, nil
}
func fetchACRToken(tenantId, token, registry string) (string, error) {
formData := url.Values{
"grant_type": {"access_token"},
"service": {registry},
"tenant": {tenantId},
"access_token": {token},
}
jsonResponse, err := http.PostForm(fmt.Sprintf("https://%s/oauth2/exchange", registry), formData)
if err != nil {
return "", errors.Wrap(err, "failed to fetch ACR token")
}
var response map[string]interface{}
err = json.NewDecoder(jsonResponse.Body).Decode(&response)
if err != nil {
return "", errors.Wrap(err, "failed to decode oauth exchange response")
}
if x, found := response["refresh_token"]; found {
s, ok := x.(string)
if !ok {
errors.New("failed to cast refresh token from acr")
} else {
return s, nil
}
} else {
return "", errors.Wrap(err, "refresh token not found in response of oauth exchange call")
}
return "", errors.New("failed to get refresh token from acr")
}
func setupACRCert(cert string) error {
decoded, err := base64.StdEncoding.DecodeString(cert)
if err != nil {
return errors.Wrap(err, "failed to base64 decode ACR certificate")
}
err = ioutil.WriteFile(ACRCertPath, []byte(decoded), 0644)
if err != nil {
return errors.Wrap(err, "failed to write ACR certificate")
}
return nil
}
func getPublicUrl(token, registryUrl, subscriptionId string) (string, error) {
// for backward compatibilty, if the subscription id is not defined, do not fail step.
if len(subscriptionId) == 0 {
return "", nil
}
registry := strings.Split(registryUrl, ".")[0]
baseURL := "https://management.azure.com/subscriptions/" +
subscriptionId + "/resources?$filter=resourceType%20eq%20'Microsoft.ContainerRegistry/registries'%20and%20name%20eq%20'" +
registry + "'&api-version=2021-04-01&$select=id"
method := "GET"
client := &http.Client{}
cnt := 0
for {
// this is just in case we end up cycling through nextLink's infinitely.
// this should not happen - added as a precaution.
if cnt > maxPageCount {
break
}
cnt++
req, err := http.NewRequest(method, baseURL, nil)
if err != nil {
return "", errors.Wrap(err, "failed to create request for getting container registry setting")
}
req.Header.Add("Authorization", "Bearer "+token)
res, err := client.Do(req)
if err != nil {
return "", errors.Wrap(err, "failed to send request for getting container registry setting")
}
defer res.Body.Close()
var response strct
err = json.NewDecoder(res.Body).Decode(&response)
if err != nil {
return "", errors.Wrap(err, "failed to send request for getting container registry setting")
}
if len(response.Value) > 0 {
if response.Value[0].ID == "" { // should not happen
return "", errors.New("received empty registry ID from /subscriptions API")
}
return finalUrl + encodeParam(response.Value[0].ID), nil
}
if response.NextLink == "" {
// No more pages, break the loop
break
}
baseURL = response.NextLink
}
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)
}
type strct struct {
Value []struct {
ID string `json:"id"`
} `json:"value"`
NextLink string `json:"nextLink"` // for pagination
}