|
| 1 | +package fastly |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io/ioutil" |
| 7 | + "log" |
| 8 | + "sort" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/hashicorp/go-cleanhttp" |
| 12 | + "github.com/hashicorp/terraform/helper/schema" |
| 13 | +) |
| 14 | + |
| 15 | +type dataSourceFastlyIPRangesResult struct { |
| 16 | + Addresses []string |
| 17 | +} |
| 18 | + |
| 19 | +func dataSourceFastlyIPRanges() *schema.Resource { |
| 20 | + return &schema.Resource{ |
| 21 | + Read: dataSourceFastlyIPRangesRead, |
| 22 | + |
| 23 | + Schema: map[string]*schema.Schema{ |
| 24 | + "blocks": &schema.Schema{ |
| 25 | + Type: schema.TypeList, |
| 26 | + Computed: true, |
| 27 | + Elem: &schema.Schema{Type: schema.TypeString}, |
| 28 | + }, |
| 29 | + }, |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +func dataSourceFastlyIPRangesRead(d *schema.ResourceData, meta interface{}) error { |
| 34 | + |
| 35 | + conn := cleanhttp.DefaultClient() |
| 36 | + |
| 37 | + log.Printf("[DEBUG] Reading IP ranges") |
| 38 | + d.SetId(time.Now().UTC().String()) |
| 39 | + |
| 40 | + res, err := conn.Get("https://api.fastly.com/public-ip-list") |
| 41 | + |
| 42 | + if err != nil { |
| 43 | + return fmt.Errorf("Error listing IP ranges: %s", err) |
| 44 | + } |
| 45 | + |
| 46 | + defer res.Body.Close() |
| 47 | + |
| 48 | + data, err := ioutil.ReadAll(res.Body) |
| 49 | + |
| 50 | + if err != nil { |
| 51 | + return fmt.Errorf("Error reading response body: %s", err) |
| 52 | + } |
| 53 | + |
| 54 | + result := new(dataSourceFastlyIPRangesResult) |
| 55 | + |
| 56 | + if err := json.Unmarshal(data, result); err != nil { |
| 57 | + return fmt.Errorf("Error parsing result: %s", err) |
| 58 | + } |
| 59 | + |
| 60 | + sort.Strings(result.Addresses) |
| 61 | + |
| 62 | + if err := d.Set("blocks", result.Addresses); err != nil { |
| 63 | + return fmt.Errorf("Error setting ip ranges: %s", err) |
| 64 | + } |
| 65 | + |
| 66 | + return nil |
| 67 | + |
| 68 | +} |
0 commit comments