From 13ea0a01c61416795b0497cee2b9dfba30438e6a Mon Sep 17 00:00:00 2001 From: Joern Barthel Date: Thu, 4 Aug 2016 19:19:43 +0200 Subject: [PATCH] Added IP ranges from Fastly --- .../providers/fastly/data_source_ip_ranges.go | 68 +++++++++++++++++++ builtin/providers/fastly/provider.go | 3 + 2 files changed, 71 insertions(+) create mode 100644 builtin/providers/fastly/data_source_ip_ranges.go diff --git a/builtin/providers/fastly/data_source_ip_ranges.go b/builtin/providers/fastly/data_source_ip_ranges.go new file mode 100644 index 000000000..bc01cd232 --- /dev/null +++ b/builtin/providers/fastly/data_source_ip_ranges.go @@ -0,0 +1,68 @@ +package fastly + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "log" + "sort" + "time" + + "github.com/hashicorp/go-cleanhttp" + "github.com/hashicorp/terraform/helper/schema" +) + +type dataSourceFastlyIPRangesResult struct { + Addresses []string +} + +func dataSourceFastlyIPRanges() *schema.Resource { + return &schema.Resource{ + Read: dataSourceFastlyIPRangesRead, + + Schema: map[string]*schema.Schema{ + "blocks": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + } +} + +func dataSourceFastlyIPRangesRead(d *schema.ResourceData, meta interface{}) error { + + conn := cleanhttp.DefaultClient() + + log.Printf("[DEBUG] Reading IP ranges") + d.SetId(time.Now().UTC().String()) + + res, err := conn.Get("https://api.fastly.com/public-ip-list") + + if err != nil { + return fmt.Errorf("Error listing IP ranges: %s", err) + } + + defer res.Body.Close() + + data, err := ioutil.ReadAll(res.Body) + + if err != nil { + return fmt.Errorf("Error reading response body: %s", err) + } + + result := new(dataSourceFastlyIPRangesResult) + + if err := json.Unmarshal(data, result); err != nil { + return fmt.Errorf("Error parsing result: %s", err) + } + + sort.Strings(result.Addresses) + + if err := d.Set("blocks", result.Addresses); err != nil { + return fmt.Errorf("Error setting ip ranges: %s", err) + } + + return nil + +} diff --git a/builtin/providers/fastly/provider.go b/builtin/providers/fastly/provider.go index f68c6705b..eee4be8e8 100644 --- a/builtin/providers/fastly/provider.go +++ b/builtin/providers/fastly/provider.go @@ -18,6 +18,9 @@ func Provider() terraform.ResourceProvider { Description: "Fastly API Key from https://app.fastly.com/#account", }, }, + DataSourcesMap: map[string]*schema.Resource{ + "fastly_ip_ranges": dataSourceFastlyIPRanges(), + }, ResourcesMap: map[string]*schema.Resource{ "fastly_service_v1": resourceServiceV1(), },