provider/cloudflare: Add proxied option (#5508)
This change adds the support for the proxied configuration option for a record which enables origin protection for CloudFlare records. In order to do so the golang library needed to be changed as the old did not support the option and was using and outdated API version. Open issues which ask for this (#5049, #3805).
This commit is contained in:
parent
d692cf5f60
commit
251075564a
|
@ -548,6 +548,10 @@
|
|||
"Comment": "v2.3.0-alpha.0-652-ge552791",
|
||||
"Rev": "e5527914aa42cae3063f52892e1ca4518da0e4ae"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/crackcomm/cloudflare",
|
||||
"Rev": "40f33bf6a6721e6d266a98d29e5a94afbe0169ed"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/cyberdelia/heroku-go/v3",
|
||||
"Rev": "81c5afa1abcf69cc18ccc24fa3716b5a455c9208"
|
||||
|
|
|
@ -1,10 +1,9 @@
|
|||
package cloudflare
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/pearkes/cloudflare"
|
||||
"github.com/crackcomm/cloudflare"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
|
@ -14,13 +13,12 @@ type Config struct {
|
|||
|
||||
// Client() returns a new client for accessing cloudflare.
|
||||
func (c *Config) Client() (*cloudflare.Client, error) {
|
||||
client, err := cloudflare.NewClient(c.Email, c.Token)
|
||||
client := cloudflare.New(&cloudflare.Options{
|
||||
Email: c.Email,
|
||||
Key: c.Token,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error setting up client: %s", err)
|
||||
}
|
||||
|
||||
log.Printf("[INFO] CloudFlare Client configured for user: %s", client.Email)
|
||||
log.Printf("[INFO] CloudFlare Client configured for user: %s", c.Email)
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
|
|
@ -38,6 +38,6 @@ func testAccPreCheck(t *testing.T) {
|
|||
}
|
||||
|
||||
if v := os.Getenv("CLOUDFLARE_DOMAIN"); v == "" {
|
||||
t.Fatal("CLOUDFLARE_DOMAIN must be set for acceptance tests. The domain is used to ` and destroy record against.")
|
||||
t.Fatal("CLOUDFLARE_DOMAIN must be set for acceptance tests. The domain is used to create and destroy record against.")
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,9 +4,12 @@ import (
|
|||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/context"
|
||||
|
||||
"github.com/crackcomm/cloudflare"
|
||||
"github.com/hashicorp/terraform/helper/schema"
|
||||
"github.com/pearkes/cloudflare"
|
||||
)
|
||||
|
||||
func resourceCloudFlareRecord() *schema.Resource {
|
||||
|
@ -44,15 +47,26 @@ func resourceCloudFlareRecord() *schema.Resource {
|
|||
},
|
||||
|
||||
"ttl": &schema.Schema{
|
||||
Type: schema.TypeString,
|
||||
Type: schema.TypeInt,
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
|
||||
"priority": &schema.Schema{
|
||||
Type: schema.TypeString,
|
||||
Type: schema.TypeInt,
|
||||
Optional: true,
|
||||
},
|
||||
|
||||
"proxied": &schema.Schema{
|
||||
Default: false,
|
||||
Optional: true,
|
||||
Type: schema.TypeBool,
|
||||
},
|
||||
|
||||
"zone_id": &schema.Schema{
|
||||
Type: schema.TypeString,
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
@ -60,56 +74,71 @@ func resourceCloudFlareRecord() *schema.Resource {
|
|||
func resourceCloudFlareRecordCreate(d *schema.ResourceData, meta interface{}) error {
|
||||
client := meta.(*cloudflare.Client)
|
||||
|
||||
// Create the new record
|
||||
newRecord := &cloudflare.CreateRecord{
|
||||
Name: d.Get("name").(string),
|
||||
Type: d.Get("type").(string),
|
||||
Content: d.Get("value").(string),
|
||||
}
|
||||
|
||||
if ttl, ok := d.GetOk("ttl"); ok {
|
||||
newRecord.Ttl = ttl.(string)
|
||||
newRecord := &cloudflare.Record{
|
||||
Content: d.Get("value").(string),
|
||||
Name: d.Get("name").(string),
|
||||
Proxied: d.Get("proxied").(bool),
|
||||
Type: d.Get("type").(string),
|
||||
ZoneName: d.Get("domain").(string),
|
||||
}
|
||||
|
||||
if priority, ok := d.GetOk("priority"); ok {
|
||||
newRecord.Priority = priority.(string)
|
||||
newRecord.Priority = priority.(int)
|
||||
}
|
||||
|
||||
if ttl, ok := d.GetOk("ttl"); ok {
|
||||
newRecord.TTL = ttl.(int)
|
||||
}
|
||||
|
||||
zone, err := retrieveZone(client, newRecord.ZoneName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
d.Set("zone_id", zone.ID)
|
||||
newRecord.ZoneID = zone.ID
|
||||
|
||||
log.Printf("[DEBUG] CloudFlare Record create configuration: %#v", newRecord)
|
||||
|
||||
rec, err := client.CreateRecord(d.Get("domain").(string), newRecord)
|
||||
ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
|
||||
|
||||
err = client.Records.Create(ctx, newRecord)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to create CloudFlare Record: %s", err)
|
||||
return fmt.Errorf("Failed to create record: %s", err)
|
||||
}
|
||||
|
||||
d.SetId(rec.Id)
|
||||
d.SetId(newRecord.ID)
|
||||
|
||||
log.Printf("[INFO] CloudFlare Record ID: %s", d.Id())
|
||||
|
||||
return resourceCloudFlareRecordRead(d, meta)
|
||||
}
|
||||
|
||||
func resourceCloudFlareRecordRead(d *schema.ResourceData, meta interface{}) error {
|
||||
client := meta.(*cloudflare.Client)
|
||||
var (
|
||||
client = meta.(*cloudflare.Client)
|
||||
domain = d.Get("domain").(string)
|
||||
rName = strings.Join([]string{d.Get("name").(string), domain}, ".")
|
||||
)
|
||||
|
||||
rec, err := client.RetrieveRecord(d.Get("domain").(string), d.Id())
|
||||
zone, err := retrieveZone(client, domain)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
d.SetId("")
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf(
|
||||
"Couldn't find CloudFlare Record ID (%s) for domain (%s): %s",
|
||||
d.Id(), d.Get("domain").(string), err)
|
||||
return err
|
||||
}
|
||||
|
||||
d.Set("name", rec.Name)
|
||||
d.Set("hostname", rec.FullName)
|
||||
d.Set("type", rec.Type)
|
||||
d.Set("value", rec.Value)
|
||||
d.Set("ttl", rec.Ttl)
|
||||
d.Set("priority", rec.Priority)
|
||||
record, err := retrieveRecord(client, zone, rName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
d.SetId(record.ID)
|
||||
d.Set("hostname", record.Name)
|
||||
d.Set("type", record.Type)
|
||||
d.Set("value", record.Content)
|
||||
d.Set("ttl", record.TTL)
|
||||
d.Set("priority", record.Priority)
|
||||
d.Set("proxied", record.Proxied)
|
||||
d.Set("zone_id", zone.ID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
@ -117,24 +146,39 @@ func resourceCloudFlareRecordRead(d *schema.ResourceData, meta interface{}) erro
|
|||
func resourceCloudFlareRecordUpdate(d *schema.ResourceData, meta interface{}) error {
|
||||
client := meta.(*cloudflare.Client)
|
||||
|
||||
// CloudFlare requires we send all values for an update request
|
||||
updateRecord := &cloudflare.UpdateRecord{
|
||||
Name: d.Get("name").(string),
|
||||
Type: d.Get("type").(string),
|
||||
Content: d.Get("value").(string),
|
||||
}
|
||||
|
||||
if ttl, ok := d.GetOk("ttl"); ok {
|
||||
updateRecord.Ttl = ttl.(string)
|
||||
updateRecord := &cloudflare.Record{
|
||||
Content: d.Get("value").(string),
|
||||
ID: d.Id(),
|
||||
Name: d.Get("name").(string),
|
||||
Proxied: false,
|
||||
Type: d.Get("type").(string),
|
||||
ZoneName: d.Get("domain").(string),
|
||||
}
|
||||
|
||||
if priority, ok := d.GetOk("priority"); ok {
|
||||
updateRecord.Priority = priority.(string)
|
||||
updateRecord.Priority = priority.(int)
|
||||
}
|
||||
|
||||
if proxied, ok := d.GetOk("proxied"); ok {
|
||||
updateRecord.Proxied = proxied.(bool)
|
||||
}
|
||||
|
||||
if ttl, ok := d.GetOk("ttl"); ok {
|
||||
updateRecord.TTL = ttl.(int)
|
||||
}
|
||||
|
||||
zone, err := retrieveZone(client, updateRecord.ZoneName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
updateRecord.ZoneID = zone.ID
|
||||
|
||||
log.Printf("[DEBUG] CloudFlare Record update configuration: %#v", updateRecord)
|
||||
|
||||
err := client.UpdateRecord(d.Get("domain").(string), d.Id(), updateRecord)
|
||||
ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
|
||||
|
||||
err = client.Records.Patch(ctx, updateRecord)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to update CloudFlare Record: %s", err)
|
||||
}
|
||||
|
@ -143,15 +187,79 @@ func resourceCloudFlareRecordUpdate(d *schema.ResourceData, meta interface{}) er
|
|||
}
|
||||
|
||||
func resourceCloudFlareRecordDelete(d *schema.ResourceData, meta interface{}) error {
|
||||
client := meta.(*cloudflare.Client)
|
||||
var (
|
||||
client = meta.(*cloudflare.Client)
|
||||
domain = d.Get("domain").(string)
|
||||
rName = strings.Join([]string{d.Get("name").(string), domain}, ".")
|
||||
)
|
||||
|
||||
log.Printf("[INFO] Deleting CloudFlare Record: %s, %s", d.Get("domain").(string), d.Id())
|
||||
zone, err := retrieveZone(client, domain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err := client.DestroyRecord(d.Get("domain").(string), d.Id())
|
||||
record, err := retrieveRecord(client, zone, rName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Printf("[INFO] Deleting CloudFlare Record: %s, %s", domain, d.Id())
|
||||
|
||||
ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
|
||||
|
||||
err = client.Records.Delete(ctx, zone.ID, record.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error deleting CloudFlare Record: %s", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func retrieveRecord(
|
||||
client *cloudflare.Client,
|
||||
zone *cloudflare.Zone,
|
||||
name string,
|
||||
) (*cloudflare.Record, error) {
|
||||
ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
|
||||
|
||||
rs, err := client.Records.List(ctx, zone.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Unable to retrieve records for (%s): %s", zone.Name, err)
|
||||
}
|
||||
|
||||
var record *cloudflare.Record
|
||||
|
||||
for _, r := range rs {
|
||||
if r.Name == name {
|
||||
record = r
|
||||
}
|
||||
}
|
||||
if record == nil {
|
||||
return nil, fmt.Errorf("Unable to find Cloudflare record %s", name)
|
||||
}
|
||||
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func retrieveZone(client *cloudflare.Client, domain string) (*cloudflare.Zone, error) {
|
||||
ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
|
||||
|
||||
zs, err := client.Zones.List(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to fetch zone for %s: %s", domain, err)
|
||||
}
|
||||
|
||||
var zone *cloudflare.Zone
|
||||
|
||||
for _, z := range zs {
|
||||
if z.Name == domain {
|
||||
zone = z
|
||||
}
|
||||
}
|
||||
|
||||
if zone == nil {
|
||||
return nil, fmt.Errorf("Failed to find zone for: %s", domain)
|
||||
}
|
||||
|
||||
return zone, nil
|
||||
}
|
||||
|
|
|
@ -4,26 +4,29 @@ import (
|
|||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/context"
|
||||
|
||||
"github.com/crackcomm/cloudflare"
|
||||
"github.com/hashicorp/terraform/helper/resource"
|
||||
"github.com/hashicorp/terraform/terraform"
|
||||
"github.com/pearkes/cloudflare"
|
||||
)
|
||||
|
||||
func TestAccCLOudflareRecord_Basic(t *testing.T) {
|
||||
func TestAccCloudFlareRecord_Basic(t *testing.T) {
|
||||
var record cloudflare.Record
|
||||
domain := os.Getenv("CLOUDFLARE_DOMAIN")
|
||||
|
||||
resource.Test(t, resource.TestCase{
|
||||
PreCheck: func() { testAccPreCheck(t) },
|
||||
Providers: testAccProviders,
|
||||
CheckDestroy: testAccCheckCLOudflareRecordDestroy,
|
||||
CheckDestroy: testAccCheckCloudFlareRecordDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
resource.TestStep{
|
||||
Config: fmt.Sprintf(testAccCheckCLoudFlareRecordConfig_basic, domain),
|
||||
Config: fmt.Sprintf(testAccCheckCloudFlareRecordConfigBasic, domain),
|
||||
Check: resource.ComposeTestCheckFunc(
|
||||
testAccCheckCLOudflareRecordExists("cloudflare_record.foobar", &record),
|
||||
testAccCheckCLOudflareRecordAttributes(&record),
|
||||
testAccCheckCloudFlareRecordExists("cloudflare_record.foobar", &record),
|
||||
testAccCheckCloudFlareRecordAttributes(&record),
|
||||
resource.TestCheckResourceAttr(
|
||||
"cloudflare_record.foobar", "name", "terraform"),
|
||||
resource.TestCheckResourceAttr(
|
||||
|
@ -36,20 +39,49 @@ func TestAccCLOudflareRecord_Basic(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func TestAccCLOudflareRecord_Updated(t *testing.T) {
|
||||
func TestAccCloudFlareRecord_Proxied(t *testing.T) {
|
||||
var record cloudflare.Record
|
||||
domain := os.Getenv("CLOUDFLARE_DOMAIN")
|
||||
|
||||
resource.Test(t, resource.TestCase{
|
||||
PreCheck: func() { testAccPreCheck(t) },
|
||||
Providers: testAccProviders,
|
||||
CheckDestroy: testAccCheckCLOudflareRecordDestroy,
|
||||
CheckDestroy: testAccCheckCloudFlareRecordDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
resource.TestStep{
|
||||
Config: fmt.Sprintf(testAccCheckCLoudFlareRecordConfig_basic, domain),
|
||||
Config: fmt.Sprintf(testAccCheckCloudFlareRecordConfigProxied, domain, domain),
|
||||
Check: resource.ComposeTestCheckFunc(
|
||||
testAccCheckCLOudflareRecordExists("cloudflare_record.foobar", &record),
|
||||
testAccCheckCLOudflareRecordAttributes(&record),
|
||||
testAccCheckCloudFlareRecordExists("cloudflare_record.foobar", &record),
|
||||
resource.TestCheckResourceAttr(
|
||||
"cloudflare_record.foobar", "domain", domain),
|
||||
resource.TestCheckResourceAttr(
|
||||
"cloudflare_record.foobar", "name", "terraform"),
|
||||
resource.TestCheckResourceAttr(
|
||||
"cloudflare_record.foobar", "proxied", "true"),
|
||||
resource.TestCheckResourceAttr(
|
||||
"cloudflare_record.foobar", "type", "CNAME"),
|
||||
resource.TestCheckResourceAttr(
|
||||
"cloudflare_record.foobar", "value", domain),
|
||||
),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestAccCloudFlareRecord_Updated(t *testing.T) {
|
||||
var record cloudflare.Record
|
||||
domain := os.Getenv("CLOUDFLARE_DOMAIN")
|
||||
|
||||
resource.Test(t, resource.TestCase{
|
||||
PreCheck: func() { testAccPreCheck(t) },
|
||||
Providers: testAccProviders,
|
||||
CheckDestroy: testAccCheckCloudFlareRecordDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
resource.TestStep{
|
||||
Config: fmt.Sprintf(testAccCheckCloudFlareRecordConfigBasic, domain),
|
||||
Check: resource.ComposeTestCheckFunc(
|
||||
testAccCheckCloudFlareRecordExists("cloudflare_record.foobar", &record),
|
||||
testAccCheckCloudFlareRecordAttributes(&record),
|
||||
resource.TestCheckResourceAttr(
|
||||
"cloudflare_record.foobar", "name", "terraform"),
|
||||
resource.TestCheckResourceAttr(
|
||||
|
@ -59,10 +91,10 @@ func TestAccCLOudflareRecord_Updated(t *testing.T) {
|
|||
),
|
||||
},
|
||||
resource.TestStep{
|
||||
Config: fmt.Sprintf(testAccCheckCloudFlareRecordConfig_new_value, domain),
|
||||
Config: fmt.Sprintf(testAccCheckCloudFlareRecordConfigNewValue, domain),
|
||||
Check: resource.ComposeTestCheckFunc(
|
||||
testAccCheckCLOudflareRecordExists("cloudflare_record.foobar", &record),
|
||||
testAccCheckCLOudflareRecordAttributesUpdated(&record),
|
||||
testAccCheckCloudFlareRecordExists("cloudflare_record.foobar", &record),
|
||||
testAccCheckCloudFlareRecordAttributesUpdated(&record),
|
||||
resource.TestCheckResourceAttr(
|
||||
"cloudflare_record.foobar", "name", "terraform"),
|
||||
resource.TestCheckResourceAttr(
|
||||
|
@ -75,25 +107,25 @@ func TestAccCLOudflareRecord_Updated(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func TestAccCLOudflareRecord_forceNewRecord(t *testing.T) {
|
||||
func TestAccCloudFlareRecord_forceNewRecord(t *testing.T) {
|
||||
var afterCreate, afterUpdate cloudflare.Record
|
||||
domain := os.Getenv("CLOUDFLARE_DOMAIN")
|
||||
|
||||
resource.Test(t, resource.TestCase{
|
||||
PreCheck: func() { testAccPreCheck(t) },
|
||||
Providers: testAccProviders,
|
||||
CheckDestroy: testAccCheckCLOudflareRecordDestroy,
|
||||
CheckDestroy: testAccCheckCloudFlareRecordDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
resource.TestStep{
|
||||
Config: fmt.Sprintf(testAccCheckCLoudFlareRecordConfig_basic, domain),
|
||||
Config: fmt.Sprintf(testAccCheckCloudFlareRecordConfigBasic, domain),
|
||||
Check: resource.ComposeTestCheckFunc(
|
||||
testAccCheckCLOudflareRecordExists("cloudflare_record.foobar", &afterCreate),
|
||||
testAccCheckCloudFlareRecordExists("cloudflare_record.foobar", &afterCreate),
|
||||
),
|
||||
},
|
||||
resource.TestStep{
|
||||
Config: fmt.Sprintf(testAccCheckCloudFlareRecordConfig_forceNew, domain, domain),
|
||||
Config: fmt.Sprintf(testAccCheckCloudFlareRecordConfigForceNew, domain, domain),
|
||||
Check: resource.ComposeTestCheckFunc(
|
||||
testAccCheckCLOudflareRecordExists("cloudflare_record.foobar", &afterUpdate),
|
||||
testAccCheckCloudFlareRecordExists("cloudflare_record.foobar", &afterUpdate),
|
||||
testAccCheckCloudFlareRecordRecreated(t, &afterCreate, &afterUpdate),
|
||||
),
|
||||
},
|
||||
|
@ -104,23 +136,25 @@ func TestAccCLOudflareRecord_forceNewRecord(t *testing.T) {
|
|||
func testAccCheckCloudFlareRecordRecreated(t *testing.T,
|
||||
before, after *cloudflare.Record) resource.TestCheckFunc {
|
||||
return func(s *terraform.State) error {
|
||||
if before.Id == after.Id {
|
||||
t.Fatalf("Expected change of Record Ids, but both were %v", before.Id)
|
||||
if before.ID == after.ID {
|
||||
t.Fatalf("Expected change of Record Ids, but both were %v", before.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func testAccCheckCLOudflareRecordDestroy(s *terraform.State) error {
|
||||
client := testAccProvider.Meta().(*cloudflare.Client)
|
||||
func testAccCheckCloudFlareRecordDestroy(s *terraform.State) error {
|
||||
var (
|
||||
client = testAccProvider.Meta().(*cloudflare.Client)
|
||||
ctx, _ = context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
|
||||
)
|
||||
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "cloudflare_record" {
|
||||
continue
|
||||
}
|
||||
|
||||
_, err := client.RetrieveRecord(rs.Primary.Attributes["domain"], rs.Primary.ID)
|
||||
|
||||
_, err := client.Records.Details(ctx, rs.Primary.Attributes["zone_id"], rs.Primary.ID)
|
||||
if err == nil {
|
||||
return fmt.Errorf("Record still exists")
|
||||
}
|
||||
|
@ -129,32 +163,31 @@ func testAccCheckCLOudflareRecordDestroy(s *terraform.State) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func testAccCheckCLOudflareRecordAttributes(record *cloudflare.Record) resource.TestCheckFunc {
|
||||
func testAccCheckCloudFlareRecordAttributes(record *cloudflare.Record) resource.TestCheckFunc {
|
||||
return func(s *terraform.State) error {
|
||||
|
||||
if record.Value != "192.168.0.10" {
|
||||
return fmt.Errorf("Bad value: %s", record.Value)
|
||||
if record.Content != "192.168.0.10" {
|
||||
return fmt.Errorf("Bad content: %s", record.Content)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func testAccCheckCLOudflareRecordAttributesUpdated(record *cloudflare.Record) resource.TestCheckFunc {
|
||||
func testAccCheckCloudFlareRecordAttributesUpdated(record *cloudflare.Record) resource.TestCheckFunc {
|
||||
return func(s *terraform.State) error {
|
||||
|
||||
if record.Value != "192.168.0.11" {
|
||||
return fmt.Errorf("Bad value: %s", record.Value)
|
||||
if record.Content != "192.168.0.11" {
|
||||
return fmt.Errorf("Bad content: %s", record.Content)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func testAccCheckCLOudflareRecordExists(n string, record *cloudflare.Record) resource.TestCheckFunc {
|
||||
func testAccCheckCloudFlareRecordExists(n string, record *cloudflare.Record) resource.TestCheckFunc {
|
||||
return func(s *terraform.State) error {
|
||||
rs, ok := s.RootModule().Resources[n]
|
||||
|
||||
if !ok {
|
||||
return fmt.Errorf("Not found: %s", n)
|
||||
}
|
||||
|
@ -163,15 +196,17 @@ func testAccCheckCLOudflareRecordExists(n string, record *cloudflare.Record) res
|
|||
return fmt.Errorf("No Record ID is set")
|
||||
}
|
||||
|
||||
client := testAccProvider.Meta().(*cloudflare.Client)
|
||||
|
||||
foundRecord, err := client.RetrieveRecord(rs.Primary.Attributes["domain"], rs.Primary.ID)
|
||||
var (
|
||||
client = testAccProvider.Meta().(*cloudflare.Client)
|
||||
ctx, _ = context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
|
||||
)
|
||||
|
||||
foundRecord, err := client.Records.Details(ctx, rs.Primary.Attributes["zone_id"], rs.Primary.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if foundRecord.Id != rs.Primary.ID {
|
||||
if foundRecord.ID != rs.Primary.ID {
|
||||
return fmt.Errorf("Record not found")
|
||||
}
|
||||
|
||||
|
@ -181,7 +216,7 @@ func testAccCheckCLOudflareRecordExists(n string, record *cloudflare.Record) res
|
|||
}
|
||||
}
|
||||
|
||||
const testAccCheckCLoudFlareRecordConfig_basic = `
|
||||
const testAccCheckCloudFlareRecordConfigBasic = `
|
||||
resource "cloudflare_record" "foobar" {
|
||||
domain = "%s"
|
||||
|
||||
|
@ -191,7 +226,17 @@ resource "cloudflare_record" "foobar" {
|
|||
ttl = 3600
|
||||
}`
|
||||
|
||||
const testAccCheckCloudFlareRecordConfig_new_value = `
|
||||
const testAccCheckCloudFlareRecordConfigProxied = `
|
||||
resource "cloudflare_record" "foobar" {
|
||||
domain = "%s"
|
||||
|
||||
name = "terraform"
|
||||
value = "%s"
|
||||
type = "CNAME"
|
||||
proxied = true
|
||||
}`
|
||||
|
||||
const testAccCheckCloudFlareRecordConfigNewValue = `
|
||||
resource "cloudflare_record" "foobar" {
|
||||
domain = "%s"
|
||||
|
||||
|
@ -201,7 +246,7 @@ resource "cloudflare_record" "foobar" {
|
|||
ttl = 3600
|
||||
}`
|
||||
|
||||
const testAccCheckCloudFlareRecordConfig_forceNew = `
|
||||
const testAccCheckCloudFlareRecordConfigForceNew = `
|
||||
resource "cloudflare_record" "foobar" {
|
||||
domain = "%s"
|
||||
|
||||
|
|
|
@ -0,0 +1,26 @@
|
|||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
||||
|
||||
dist/
|
|
@ -0,0 +1,4 @@
|
|||
FROM busybox
|
||||
MAINTAINER Łukasz Kurowski <crackcomm@gmail.com>
|
||||
COPY ./dist/cf /cf
|
||||
ENTRYPOINT ["/cf"]
|
|
@ -0,0 +1,202 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
|
||||
save-godeps:
|
||||
godep save github.com/crackcomm/cloudflare/cf
|
||||
|
||||
cloudflare-build:
|
||||
mkdir -p dist
|
||||
CGO_ENABLED=0 GOOS=linux go build -ldflags "-s" -a -installsuffix cgo -o ./dist/cf ./cf/main.go
|
||||
|
||||
install:
|
||||
go install github.com/crackcomm/cloudflare/cf
|
||||
|
||||
dist: cloudflare-build
|
||||
|
||||
clean:
|
||||
rm -rf dist
|
|
@ -0,0 +1,98 @@
|
|||
# Golang CloudFlare® API v4 client
|
||||
|
||||
[![GoDoc](https://godoc.org/github.com/crackcomm/cloudflare?status.svg)](https://godoc.org/github.com/crackcomm/cloudflare) [![Circle CI](https://img.shields.io/circleci/project/crackcomm/cloudflare.svg)](https://circleci.com/gh/crackcomm/cloudflare)
|
||||
|
||||
|
||||
Golang API Client for CloudFlare® API v4.
|
||||
|
||||
## Command Line Tool
|
||||
|
||||
```sh
|
||||
$ go install github.com/crackcomm/cloudflare/cf
|
||||
$ cf
|
||||
NAME:
|
||||
cf - CloudFlare command line tool
|
||||
|
||||
USAGE:
|
||||
cf [global options] command [command options] [arguments...]
|
||||
|
||||
VERSION:
|
||||
1.0.0
|
||||
|
||||
COMMANDS:
|
||||
zones zones management
|
||||
records zone records management
|
||||
help, h Shows a list of commands or help for one command
|
||||
|
||||
GLOBAL OPTIONS:
|
||||
--email CloudFlare user email [$CLOUDFLARE_EMAIL]
|
||||
--key CloudFlare user key [$CLOUDFLARE_KEY]
|
||||
--help, -h show help
|
||||
--version, -v print the version
|
||||
|
||||
$ cf zones list
|
||||
+----------------------------------+-------------------+--------+---------+
|
||||
| ID | NAME | PAUSED | STATUS |
|
||||
+----------------------------------+-------------------+--------+---------+
|
||||
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxxxxxxxxx.com | no | pending |
|
||||
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxxxxxxxxx.com | no | pending |
|
||||
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxxxxxxxxx.com | no | active |
|
||||
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxxxxxxxxx.com | no | active |
|
||||
+----------------------------------+-------------------+--------+---------+
|
||||
$ cf records list 5xxxxxcxxxxxxxxxxxxxxxxxxxxxxxx2
|
||||
+----------------------------------+------+------------------+-------------+-----------+---------+--------+-----+---------------------+---------------------+
|
||||
| ID | TYPE | NAME | CONTENT | PROXIABLE | PROXIED | LOCKED | TTL | CREATED ON | MODIFIED ON |
|
||||
+----------------------------------+------+------------------+-------------+-----------+---------+--------+-----+---------------------+---------------------+
|
||||
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | A | xxxxxxxxx.pl | xx.xx.xx.xx | yes | yes | no | 1 | 2015/01/13 15:53:59 | 2015/01/13 15:53:59 |
|
||||
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | A | www.xxxxxxxxx.pl | xx.xx.xx.xx | yes | yes | no | 1 | 2015/01/13 15:53:59 | 2015/01/13 15:53:59 |
|
||||
+----------------------------------+------+------------------+-------------+-----------+---------+--------+-----+---------------------+---------------------+
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/crackcomm/cloudflare"
|
||||
|
||||
"golang.org/x/net/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
client := cloudflare.New(&cloudflare.Options{
|
||||
Email: "example@email.com",
|
||||
Key: "example-key",
|
||||
})
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, _ = context.WithTimeout(ctx, time.Second*30)
|
||||
|
||||
zones, err := client.Zones.List(ctx)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
} else if len(zones) == 0 {
|
||||
log.Fatal("No zones were found")
|
||||
}
|
||||
|
||||
records, err := client.Records.List(ctx, zones[0].ID)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for _, record := range records {
|
||||
log.Printf("%#v", record)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## CloudFlare®
|
||||
|
||||
CloudFlare is a registered trademark of [CloudFlare, Inc](https://cloudflare.com).
|
||||
|
||||
## License
|
||||
|
||||
Apache 2.0 License.
|
|
@ -0,0 +1,14 @@
|
|||
|
||||
machine:
|
||||
services:
|
||||
- docker
|
||||
|
||||
deployment:
|
||||
staging:
|
||||
branch: master
|
||||
commands:
|
||||
- docker login -e $DOCKER_EMAIL -u $DOCKER_USER -p $DOCKER_PASS
|
||||
- make dist
|
||||
- docker build -t crackcomm/cf:latest .
|
||||
- docker push crackcomm/cf:latest
|
||||
- make clean
|
|
@ -0,0 +1,24 @@
|
|||
package cloudflare
|
||||
|
||||
// Options - Cloudflare API Client Options.
|
||||
type Options struct {
|
||||
Email, Key string
|
||||
}
|
||||
|
||||
// Client - Cloudflare API Client.
|
||||
type Client struct {
|
||||
*Zones
|
||||
*Records
|
||||
*Firewalls
|
||||
opts *Options
|
||||
}
|
||||
|
||||
// New - Creates a new Cloudflare client.
|
||||
func New(opts *Options) *Client {
|
||||
return &Client{
|
||||
Zones: &Zones{opts: opts},
|
||||
Records: &Records{opts: opts},
|
||||
Firewalls: &Firewalls{opts: opts},
|
||||
opts: opts,
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package cloudflare
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/net/context"
|
||||
)
|
||||
|
||||
var baseURL = "https://api.cloudflare.com/client/v4"
|
||||
|
||||
func apiURL(format string, a ...interface{}) string {
|
||||
return fmt.Sprintf("%s%s", baseURL, fmt.Sprintf(format, a...))
|
||||
}
|
||||
|
||||
func readResponse(r io.Reader) (result *Response, err error) {
|
||||
result = new(Response)
|
||||
err = json.NewDecoder(r).Decode(result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if err := result.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type httpResponse struct {
|
||||
resp *http.Response
|
||||
err error
|
||||
}
|
||||
|
||||
func httpDo(ctx context.Context, opts *Options, method, url string, body io.Reader) (*http.Response, error) {
|
||||
req, err := http.NewRequest(method, url, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Auth-Email", opts.Email)
|
||||
req.Header.Set("X-Auth-Key", opts.Key)
|
||||
|
||||
transport := &http.Transport{}
|
||||
client := &http.Client{Transport: transport}
|
||||
|
||||
respchan := make(chan *httpResponse, 1)
|
||||
go func() {
|
||||
resp, err := client.Do(req)
|
||||
respchan <- &httpResponse{resp: resp, err: err}
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
transport.CancelRequest(req)
|
||||
<-respchan
|
||||
return nil, ctx.Err()
|
||||
case r := <-respchan:
|
||||
return r.resp, r.err
|
||||
}
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
package cloudflare
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
"golang.org/x/net/context"
|
||||
)
|
||||
|
||||
// Firewalls - Cloudflare Fireall Zones API Client.
|
||||
type Firewalls struct {
|
||||
opts *Options
|
||||
}
|
||||
|
||||
// Create - Creates a firewall rule for zone.
|
||||
func (firewalls *Firewalls) Create(ctx context.Context, id string, firewall *Firewall) (fw *Firewall, err error) {
|
||||
buffer := new(bytes.Buffer)
|
||||
err = json.NewEncoder(buffer).Encode(firewall)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
response, err := httpDo(ctx, firewalls.opts, "POST", apiURL("/zones/%s/firewall/access_rules/rules", id), buffer)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
result, err := readResponse(response.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
fw = new(Firewall)
|
||||
err = json.Unmarshal(result.Result, &fw)
|
||||
return
|
||||
}
|
||||
|
||||
// List - Lists all firewall rules for zone.
|
||||
func (firewalls *Firewalls) List(ctx context.Context, zone string) ([]*Firewall, error) {
|
||||
return firewalls.listPages(ctx, zone, 1)
|
||||
}
|
||||
|
||||
// Delete - Deletes firewall by id.
|
||||
func (firewalls *Firewalls) Delete(ctx context.Context, zone, id string) (err error) {
|
||||
response, err := httpDo(ctx, firewalls.opts, "DELETE", apiURL("/zones/%s/firewall/access_rules/rules/%s", zone, id), nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, err = readResponse(response.Body)
|
||||
return
|
||||
}
|
||||
|
||||
// listPages - Gets all pages starting from `page`.
|
||||
func (firewalls *Firewalls) listPages(ctx context.Context, zone string, page int) (list []*Firewall, err error) {
|
||||
response, err := httpDo(ctx, firewalls.opts, "GET", apiURL("/zones/%s/firewall/access_rules/rules?page=%d&per_page=50", zone, page), nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
result, err := readResponse(response.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(result.Result, &list)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if result.ResultInfo == nil || page >= result.ResultInfo.TotalPages {
|
||||
return
|
||||
}
|
||||
next, err := firewalls.listPages(ctx, zone, page+1)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return append(list, next...), nil
|
||||
}
|
|
@ -0,0 +1,104 @@
|
|||
package cloudflare
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
"golang.org/x/net/context"
|
||||
)
|
||||
|
||||
// Records - Cloudflare Records API Client.
|
||||
type Records struct {
|
||||
opts *Options
|
||||
}
|
||||
|
||||
// Create - Creates a zone DNS record.
|
||||
// Required parameters of a record are - `type`, `name` and `content`.
|
||||
// Optional parameters of a record are - `ttl`.
|
||||
func (records *Records) Create(ctx context.Context, record *Record) (err error) {
|
||||
buffer := new(bytes.Buffer)
|
||||
err = json.NewEncoder(buffer).Encode(record)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
response, err := httpDo(ctx, records.opts, "POST", apiURL("/zones/%s/dns_records", record.ZoneID), buffer)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, err = readResponse(response.Body)
|
||||
return
|
||||
}
|
||||
|
||||
// List - Lists all zone DNS records.
|
||||
func (records *Records) List(ctx context.Context, zoneID string) ([]*Record, error) {
|
||||
return records.listPages(ctx, zoneID, 1)
|
||||
}
|
||||
|
||||
// Details - Requests zone DNS record details by zone ID and record ID.
|
||||
func (records *Records) Details(ctx context.Context, zoneID, recordID string) (record *Record, err error) {
|
||||
response, err := httpDo(ctx, records.opts, "GET", apiURL("/zones/%s/dns_records/%s", zoneID, recordID), nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
result, err := readResponse(response.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
record = new(Record)
|
||||
err = json.Unmarshal(result.Result, &record)
|
||||
return
|
||||
}
|
||||
|
||||
// Patch - Patches a zone DNS record.
|
||||
func (records *Records) Patch(ctx context.Context, record *Record) (err error) {
|
||||
buffer := new(bytes.Buffer)
|
||||
err = json.NewEncoder(buffer).Encode(record)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
response, err := httpDo(ctx, records.opts, "PUT", apiURL("/zones/%s/dns_records/%s", record.ZoneID, record.ID), buffer)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, err = readResponse(response.Body)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete - Deletes zone DNS record by zone ID and record ID.
|
||||
func (records *Records) Delete(ctx context.Context, zoneID, recordID string) (err error) {
|
||||
response, err := httpDo(ctx, records.opts, "DELETE", apiURL("/zones/%s/dns_records/%s", zoneID, recordID), nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, err = readResponse(response.Body)
|
||||
return
|
||||
}
|
||||
|
||||
// listPages - Gets all pages starting from `page`.
|
||||
func (records *Records) listPages(ctx context.Context, zoneID string, page int) (list []*Record, err error) {
|
||||
response, err := httpDo(ctx, records.opts, "GET", apiURL("/zones/%s/dns_records?page=%d&per_page=50", zoneID, page), nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
result, err := readResponse(response.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(result.Result, &list)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if result.ResultInfo == nil || page >= result.ResultInfo.TotalPages {
|
||||
return
|
||||
}
|
||||
next, err := records.listPages(ctx, zoneID, page+1)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return append(list, next...), nil
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
package cloudflare
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
"golang.org/x/net/context"
|
||||
)
|
||||
|
||||
// Zones - Cloudflare Zones API Client.
|
||||
type Zones struct {
|
||||
opts *Options
|
||||
}
|
||||
|
||||
// Create - Creates a zone.
|
||||
func (zones *Zones) Create(ctx context.Context, domain string) (zone *Zone, err error) {
|
||||
buffer := new(bytes.Buffer)
|
||||
err = json.NewEncoder(buffer).Encode(struct {
|
||||
Name string `json:"name"`
|
||||
}{
|
||||
Name: domain,
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
response, err := httpDo(ctx, zones.opts, "POST", apiURL("/zones"), buffer)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
result, err := readResponse(response.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
zone = new(Zone)
|
||||
err = json.Unmarshal(result.Result, &zone)
|
||||
return
|
||||
}
|
||||
|
||||
// List - Lists all zones.
|
||||
func (zones *Zones) List(ctx context.Context) ([]*Zone, error) {
|
||||
return zones.listPages(ctx, 1)
|
||||
}
|
||||
|
||||
// Details - Requests Zone details by ID.
|
||||
func (zones *Zones) Details(ctx context.Context, id string) (zone *Zone, err error) {
|
||||
response, err := httpDo(ctx, zones.opts, "GET", apiURL("/zones/%s", id), nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
result, err := readResponse(response.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
zone = new(Zone)
|
||||
err = json.Unmarshal(result.Result, &zone)
|
||||
return
|
||||
}
|
||||
|
||||
// Patch - Patches a zone. It has a limited possibilities.
|
||||
func (zones *Zones) Patch(ctx context.Context, id string, patch *ZonePatch) (err error) {
|
||||
buffer := new(bytes.Buffer)
|
||||
err = json.NewEncoder(buffer).Encode(patch)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
response, err := httpDo(ctx, zones.opts, "POST", apiURL("/zones/%s", id), buffer)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, err = readResponse(response.Body)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete - Deletes zone by id.
|
||||
func (zones *Zones) Delete(ctx context.Context, id string) (err error) {
|
||||
response, err := httpDo(ctx, zones.opts, "DELETE", apiURL("/zones/%s", id), nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, err = readResponse(response.Body)
|
||||
return
|
||||
}
|
||||
|
||||
// listPages - Gets all pages starting from `page`.
|
||||
func (zones *Zones) listPages(ctx context.Context, page int) (list []*Zone, err error) {
|
||||
response, err := httpDo(ctx, zones.opts, "GET", apiURL("/zones?page=%d&per_page=50", page), nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
result, err := readResponse(response.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(result.Result, &list)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if result.ResultInfo == nil || page >= result.ResultInfo.TotalPages {
|
||||
return
|
||||
}
|
||||
next, err := zones.listPages(ctx, page+1)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return append(list, next...), nil
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package cloudflare
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// Response - Cloudflare API Response.
|
||||
type Response struct {
|
||||
Result json.RawMessage `json:"result"`
|
||||
ResultInfo *ResultInfo `json:"result_info"`
|
||||
|
||||
Errors []*ResponseError `json:"errors"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// ResultInfo - Cloudflare API Response Result Info.
|
||||
type ResultInfo struct {
|
||||
Page int `json:"page,omitempty"`
|
||||
PerPage int `json:"per_page,omitempty"`
|
||||
TotalPages int `json:"total_pages,omitempty"`
|
||||
Count int `json:"count,omitempty"`
|
||||
TotalCount int `json:"total_count,omitempty"`
|
||||
}
|
||||
|
||||
// ResponseError - Cloudflare API Response error.
|
||||
type ResponseError struct {
|
||||
Code int `json:"code,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// Err - Gets response error if any.
|
||||
func (response *Response) Err() error {
|
||||
if len(response.Errors) > 0 {
|
||||
return response.Errors[0]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Error - Returns response error message.
|
||||
func (err *ResponseError) Error() string {
|
||||
return err.Message
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package cloudflare
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type FirewallConfiguration struct {
|
||||
Target string `json:"target,omitempty"`
|
||||
Value string `json:"value,omitempty"`
|
||||
}
|
||||
|
||||
// Firewall - Firewall for zone.
|
||||
type Firewall struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
|
||||
Notes string `json:"notes,omitempty"`
|
||||
AllowedModes []string `json:"allowed_modes,omitempty"`
|
||||
Mode string `json:"mode,omitempty"`
|
||||
|
||||
Configuration *FirewallConfiguration `json:"configuration,omitempty"`
|
||||
Scope *ZoneOwner `json:"scope,omitempty"`
|
||||
|
||||
CreatedOn time.Time `json:"created_on,omitempty"`
|
||||
ModifiedOn time.Time `json:"modified_on,omitempty"`
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package cloudflare
|
||||
|
||||
import "time"
|
||||
|
||||
// Record - Cloudflare DNS Record.
|
||||
type Record struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Content string `json:"content,omitempty"`
|
||||
|
||||
Proxiable bool `json:"proxiable,omitempty"`
|
||||
Proxied bool `json:"proxied,omitempty"`
|
||||
Locked bool `json:"locked,omitempty"`
|
||||
|
||||
TTL int `json:"ttl,omitempty"`
|
||||
Priority int `json:"priority,omitempty"`
|
||||
|
||||
CreatedOn time.Time `json:"created_on,omitempty"`
|
||||
ModifiedOn time.Time `json:"modified_on,omitempty"`
|
||||
|
||||
ZoneID string `json:"zone_id,omitempty"`
|
||||
ZoneName string `json:"zone_name,omitempty"`
|
||||
}
|
|
@ -0,0 +1,104 @@
|
|||
package cloudflare
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Zone - Cloudflare Zone.
|
||||
type Zone struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Paused bool `json:"paused,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
DevelopmentMode int `json:"development_mode,omitempty"`
|
||||
|
||||
NameServers []string `json:"name_servers,omitempty"`
|
||||
OriginalNameServers []string `json:"original_name_servers,omitempty"`
|
||||
|
||||
ModifiedOn time.Time `json:"modified_on,omitempty"`
|
||||
CreatedOn time.Time `json:"created_on,omitempty"`
|
||||
CheckedOn time.Time `json:"checked_on,omitempty"`
|
||||
|
||||
Meta *ZoneMeta `json:"meta,omitempty"`
|
||||
Owner *ZoneOwner `json:"owner,omitempty"`
|
||||
Plan *ZonePlan `json:"plan,omitempty"`
|
||||
|
||||
Permissions []string `json:"permissions,omitempty"`
|
||||
}
|
||||
|
||||
// ZoneOwner -
|
||||
type ZoneOwner struct {
|
||||
Type string `json:"type,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
}
|
||||
|
||||
// ZoneMeta -
|
||||
type ZoneMeta struct {
|
||||
Step int `json:"step,omitempty"`
|
||||
PageRuleQuota int `json:"page_rule_quota,omitempty"`
|
||||
CustomCertificateQuota int `json:"custom_certificate_quota,omitempty"`
|
||||
WildcardProxiable bool `json:"wildcard_proxiable,omitempty"`
|
||||
PhishingDetected bool `json:"phishing_detected,omitempty"`
|
||||
MultipleRailgunsAllowed bool `json:"multiple_railguns_allowed,omitempty"`
|
||||
}
|
||||
|
||||
func (m *ZoneMeta) UnmarshalJSON(data []byte) error {
|
||||
f := struct {
|
||||
Step int `json:"step,omitempty"`
|
||||
PageRuleQuota int `json:"page_rule_quota,omitempty"`
|
||||
CustomCertificateQuota *maybeNumber `json:"custom_certificate_quota,omitempty"`
|
||||
WildcardProxiable bool `json:"wildcard_proxiable,omitempty"`
|
||||
PhishingDetected bool `json:"phishing_detected,omitempty"`
|
||||
MultipleRailgunsAllowed bool `json:"multiple_railguns_allowed,omitempty"`
|
||||
}{}
|
||||
|
||||
err := json.Unmarshal(data, &f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
m.CustomCertificateQuota = f.CustomCertificateQuota.value
|
||||
m.MultipleRailgunsAllowed = f.MultipleRailgunsAllowed
|
||||
m.PageRuleQuota = f.PageRuleQuota
|
||||
m.PhishingDetected = f.PhishingDetected
|
||||
m.Step = f.Step
|
||||
m.WildcardProxiable = f.WildcardProxiable
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ZonePlan -
|
||||
type ZonePlan struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Price int `json:"price,omitempty"`
|
||||
Currency string `json:"currency,omitempty"`
|
||||
Frequency string `json:"frequency,omitempty"`
|
||||
LegacyID string `json:"legacy_id,omitempty"`
|
||||
IsSubscribed bool `json:"is_subscribed,omitempty"`
|
||||
CanSubscribe bool `json:"can_subscribe,omitempty"`
|
||||
ExternallyManaged bool `json:"externally_managed,omitempty"`
|
||||
}
|
||||
|
||||
// ZonePatch -
|
||||
type ZonePatch struct {
|
||||
Plan *ZonePlan `json:"plan,omitempty"`
|
||||
Paused bool `json:"paused,omitempty"`
|
||||
VanityNameServers []string `json:"vanity_name_servers,omitempty"`
|
||||
}
|
||||
|
||||
// maybeNumber is an intermediate type to cope with the inconsistent responses
|
||||
// for CustomCertificateQuota which can be a string or a number.
|
||||
type maybeNumber struct {
|
||||
value int
|
||||
}
|
||||
|
||||
func (m *maybeNumber) UnmarshalJSON(data []byte) error {
|
||||
data = bytes.Trim(data, `"`)
|
||||
|
||||
return json.Unmarshal(data, &m.value)
|
||||
}
|
|
@ -33,6 +33,7 @@ The following arguments are supported:
|
|||
* `type` - (Required) The type of the record
|
||||
* `ttl` - (Optional) The TTL of the record
|
||||
* `priority` - (Optional) The priority of the record
|
||||
* `proxied` - (Optional) Whether the record gets CloudFlares origin protection.
|
||||
|
||||
## Attributes Reference
|
||||
|
||||
|
@ -45,4 +46,5 @@ The following attributes are exported:
|
|||
* `ttl` - The TTL of the record
|
||||
* `priority` - The priority of the record
|
||||
* `hostname` - The FQDN of the record
|
||||
* `proxied` - (Optional) Whether the record gets CloudFlares origin protection.
|
||||
|
||||
|
|
Loading…
Reference in New Issue