diff --git a/internal/hcp/registry/types.bucket.go b/internal/hcp/registry/types.bucket.go index 597128dac..869398a24 100644 --- a/internal/hcp/registry/types.bucket.go +++ b/internal/hcp/registry/types.bucket.go @@ -64,23 +64,23 @@ func (b *Bucket) Validate() error { } // ReadFromHCLBuildBlock reads the information for initialising a Bucket from a HCL2 build block -func (b *Bucket) ReadFromHCLBuildBlock(hcpBlock *hcl2template.BuildBlock) { +func (b *Bucket) ReadFromHCLBuildBlock(build *hcl2template.BuildBlock) { if b == nil { return } - b.Description = hcpBlock.Description - hcp := hcpBlock.HCPPackerRegistry - if hcp == nil { + registryBlock := build.HCPPackerRegistry + if registryBlock == nil { return } - b.BucketLabels = hcp.BucketLabels - b.BuildLabels = hcp.BuildLabels + b.Description = registryBlock.Description + b.BucketLabels = registryBlock.BucketLabels + b.BuildLabels = registryBlock.BuildLabels // If there's already a Slug this was set from env variable. // In Packer, env variable overrides config values so we keep it that way for consistency. - if b.Slug == "" && hcp.Slug != "" { - b.Slug = hcp.Slug + if b.Slug == "" && registryBlock.Slug != "" { + b.Slug = registryBlock.Slug } } diff --git a/internal/hcp/registry/types.bucket_test.go b/internal/hcp/registry/types.bucket_test.go index 922916b46..d4cb7b1ac 100644 --- a/internal/hcp/registry/types.bucket_test.go +++ b/internal/hcp/registry/types.bucket_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" + "github.com/hashicorp/packer/hcl2template" "github.com/hashicorp/packer/internal/hcp/api" ) @@ -333,3 +334,51 @@ func TestBucket_PopulateIteration(t *testing.T) { }) } } + +func TestReadFromHCLBuildBlock(t *testing.T) { + tc := []struct { + desc string + buildBlock *hcl2template.BuildBlock + expectedBucket *Bucket + }{ + { + desc: "configure bucket using only hcp_packer_registry block", + buildBlock: &hcl2template.BuildBlock{ + HCPPackerRegistry: &hcl2template.HCPPackerRegistryBlock{ + Slug: "hcp_packer_registry-block-test", + Description: "description from hcp_packer_registry block", + BucketLabels: map[string]string{ + "org": "test", + }, + BuildLabels: map[string]string{ + "version": "1.7.0", + "based_off": "alpine", + }, + }, + }, + expectedBucket: &Bucket{ + Slug: "hcp_packer_registry-block-test", + Description: "description from hcp_packer_registry block", + BucketLabels: map[string]string{ + "org": "test", + }, + BuildLabels: map[string]string{ + "version": "1.7.0", + "based_off": "alpine", + }, + }, + }, + } + for _, tt := range tc { + tt := tt + t.Run(tt.desc, func(t *testing.T) { + bucket := &Bucket{} + bucket.ReadFromHCLBuildBlock(tt.buildBlock) + + diff := cmp.Diff(bucket, tt.expectedBucket, cmp.AllowUnexported(Bucket{})) + if diff != "" { + t.Errorf("expected the build to to have contents of hcp_packer_registry block but it does not: %v", diff) + } + }) + } +}