From 374f2fb6475f72862fd4b372b9125411847840c3 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Thu, 22 Aug 2013 14:58:21 -0700 Subject: [PATCH] builder/amazon/common: remove duplicates from ami_region /cc @jmassara --- builder/amazon/common/ami_config.go | 17 ++++++++++++++++ builder/amazon/common/ami_config_test.go | 26 +++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/builder/amazon/common/ami_config.go b/builder/amazon/common/ami_config.go index 074bd5a9c..de293731d 100644 --- a/builder/amazon/common/ami_config.go +++ b/builder/amazon/common/ami_config.go @@ -63,11 +63,28 @@ func (c *AMIConfig) Prepare(t *packer.ConfigTemplate) []error { } if len(c.AMIRegions) > 0 { + regionSet := make(map[string]struct{}) + regions := make([]string, 0, len(c.AMIRegions)) + for _, region := range c.AMIRegions { + // If we already saw the region, then don't look again + if _, ok := regionSet[region]; ok { + continue + } + + // Mark that we saw the region + regionSet[region] = struct{}{} + + // Verify the region is real if _, ok := aws.Regions[region]; !ok { errs = append(errs, fmt.Errorf("Unknown region: %s", region)) + continue } + + regions = append(regions, region) } + + c.AMIRegions = regions } if len(errs) > 0 { diff --git a/builder/amazon/common/ami_config_test.go b/builder/amazon/common/ami_config_test.go index dc0cc93df..9e2baa41d 100644 --- a/builder/amazon/common/ami_config_test.go +++ b/builder/amazon/common/ami_config_test.go @@ -1,6 +1,7 @@ package common import ( + "reflect" "testing" ) @@ -10,7 +11,7 @@ func testAMIConfig() *AMIConfig { } } -func TestAMIConfigPrepare_Region(t *testing.T) { +func TestAMIConfigPrepare_name(t *testing.T) { c := testAMIConfig() if err := c.Prepare(nil); err != nil { t.Fatalf("shouldn't have err: %s", err) @@ -21,3 +22,26 @@ func TestAMIConfigPrepare_Region(t *testing.T) { t.Fatal("should have error") } } + +func TestAMIConfigPrepare_regions(t *testing.T) { + c := testAMIConfig() + c.AMIRegions = nil + if err := c.Prepare(nil); err != nil { + t.Fatalf("shouldn't have err: %s", err) + } + + c.AMIRegions = []string{"foo"} + if err := c.Prepare(nil); err == nil { + t.Fatal("should have error") + } + + c.AMIRegions = []string{"us-east-1", "us-west-1", "us-east-1"} + if err := c.Prepare(nil); err != nil { + t.Fatalf("bad: %s", err) + } + + expected := []string{"us-east-1", "us-west-1"} + if !reflect.DeepEqual(c.AMIRegions, expected) { + t.Fatalf("bad: %#v", c.AMIRegions) + } +}