Skip to content

Commit 3dfdf55

Browse files
authored
Merge pull request #3023 from yankay/add-image-label
feat: Support creating container with labels defined by image
2 parents b5758f5 + cf5073b commit 3dfdf55

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

cmd/nerdctl/container_create_linux_test.go

+13
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,19 @@ func TestCreate(t *testing.T) {
3838
base.Cmd("logs", tID).AssertOutContains("foo")
3939
}
4040

41+
func TestCreateWithLabel(t *testing.T) {
42+
t.Parallel()
43+
base := testutil.NewBase(t)
44+
tID := testutil.Identifier(t)
45+
46+
base.Cmd("create", "--name", tID, "--label", "foo=bar", testutil.NginxAlpineImage, "echo", "foo").AssertOK()
47+
defer base.Cmd("rm", "-f", tID).Run()
48+
inspect := base.InspectContainer(tID)
49+
assert.Equal(base.T, "bar", inspect.Config.Labels["foo"])
50+
// the label `maintainer`` is defined by image
51+
assert.Equal(base.T, "NGINX Docker Maintainers <[email protected]>", inspect.Config.Labels["maintainer"])
52+
}
53+
4154
func TestCreateWithMACAddress(t *testing.T) {
4255
base := testutil.NewBase(t)
4356
tID := testutil.Identifier(t)

pkg/cmd/container/create.go

+13-3
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ func Create(ctx context.Context, client *containerd.Client, args []string, netMa
234234
}
235235
cOpts = append(cOpts, rtCOpts...)
236236

237-
lCOpts, err := withContainerLabels(options.Label, options.LabelFile)
237+
lCOpts, err := withContainerLabels(options.Label, options.LabelFile, ensuredImage)
238238
if err != nil {
239239
return nil, nil, err
240240
}
@@ -504,7 +504,15 @@ func withNerdctlOCIHook(cmd string, args []string) (oci.SpecOpts, error) {
504504
}, nil
505505
}
506506

507-
func withContainerLabels(label, labelFile []string) ([]containerd.NewContainerOpts, error) {
507+
func withContainerLabels(label, labelFile []string, ensuredImage *imgutil.EnsuredImage) ([]containerd.NewContainerOpts, error) {
508+
var opts []containerd.NewContainerOpts
509+
510+
// add labels defined by image
511+
if ensuredImage != nil {
512+
imageLabelOpts := containerd.WithAdditionalContainerLabels(ensuredImage.ImageConfig.Labels)
513+
opts = append(opts, imageLabelOpts)
514+
}
515+
508516
labelMap, err := readKVStringsMapfFromLabel(label, labelFile)
509517
if err != nil {
510518
return nil, err
@@ -517,7 +525,9 @@ func withContainerLabels(label, labelFile []string) ([]containerd.NewContainerOp
517525
}
518526
}
519527
o := containerd.WithAdditionalContainerLabels(labelMap)
520-
return []containerd.NewContainerOpts{o}, nil
528+
opts = append(opts, o)
529+
530+
return opts, nil
521531
}
522532

523533
func readKVStringsMapfFromLabel(label, labelFile []string) (map[string]string, error) {

0 commit comments

Comments
 (0)