terraform/builtin/providers/fastly/data_source_ip_ranges.go

71 lines
1.4 KiB
Go
Raw Normal View History

2016-08-04 19:19:43 +02:00
package fastly
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"sort"
2016-08-05 17:08:50 +02:00
"strconv"
2016-08-04 19:19:43 +02:00
"github.com/hashicorp/go-cleanhttp"
2016-08-05 17:08:50 +02:00
"github.com/hashicorp/terraform/helper/hashcode"
2016-08-04 19:19:43 +02:00
"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{
2016-08-05 17:12:28 +02:00
"cidr_blocks": &schema.Schema{
2016-08-04 19:19:43 +02:00
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")
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)
}
2016-08-05 17:08:50 +02:00
d.SetId(strconv.Itoa(hashcode.String(string(data))))
2016-08-04 19:19:43 +02:00
result := new(dataSourceFastlyIPRangesResult)
if err := json.Unmarshal(data, result); err != nil {
return fmt.Errorf("Error parsing result: %s", err)
}
sort.Strings(result.Addresses)
2016-08-05 17:12:28 +02:00
if err := d.Set("cidr_blocks", result.Addresses); err != nil {
2016-08-04 19:19:43 +02:00
return fmt.Errorf("Error setting ip ranges: %s", err)
}
return nil
}