Skip to content

Commit

Permalink
simplify and always reset on delete and update docs to show override …
Browse files Browse the repository at this point in the history
…behavior
  • Loading branch information
tjstansell committed Jan 19, 2022
1 parent e5565ce commit 2fb0985
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 155 deletions.
6 changes: 1 addition & 5 deletions .changelog/1399.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
```release-note:enhancement
resource/cloudflare_fallback_domain: Add `include_default_domains` (default: true) and `restore_default_domains_on_default` (default: true) fields.
```

```release-note:bug
resource/cloudflare_fallback_domain: default entries are now included by default and restored on delete.
resource/cloudflare_fallback_domain: default entries are now restored on delete.
```
42 changes: 5 additions & 37 deletions cloudflare/resource_cloudflare_fallback_domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,14 @@ package cloudflare
import (
"context"
"fmt"
"log"

cloudflare "github.com/cloudflare/cloudflare-go"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

// use this since we cannot use const for lists.
func default_domains() []string {
return []string{
"intranet", "internal", "private", "localdomain", "domain", "lan", "home",
"host", "corp", "local", "localhost", "home.arpa", "invalid", "test",
}
var default_domains = []string{
"intranet", "internal", "private", "localdomain", "domain", "lan", "home",
"host", "corp", "local", "localhost", "home.arpa", "invalid", "test",
}

func resourceCloudflareFallbackDomain() *schema.Resource {
Expand All @@ -27,7 +23,6 @@ func resourceCloudflareFallbackDomain() *schema.Resource {
Importer: &schema.ResourceImporter{
State: resourceCloudflareFallbackDomainImport,
},
CustomizeDiff: resourceCloudflareFallbackDomainDiff,
}
}

Expand All @@ -52,7 +47,6 @@ func resourceCloudflareFallbackDomainUpdate(d *schema.ResourceData, meta interfa
accountID := d.Get("account_id").(string)

domainList := expandFallbackDomains(d.Get("domains").([]interface{}))
log.Printf("[INFO] Updating Cloudflare Fallback Domain: %v", domainList)

newFallbackDomains, err := client.UpdateFallbackDomain(context.Background(), accountID, domainList)
if err != nil {
Expand All @@ -72,14 +66,7 @@ func resourceCloudflareFallbackDomainDelete(d *schema.ResourceData, meta interfa
client := meta.(*cloudflare.API)
accountID := d.Get("account_id").(string)

domainList := make([]cloudflare.FallbackDomain, 0)
if d.Get("restore_default_domains_on_delete").(bool) {
log.Printf("[INFO] Deleting Fallback Domains and restoring default entries.")
domainList = getDefaultDomains()
} else {
log.Printf("[INFO] Deleting Fallback Domains without restoring default entries.")
}
_, err := client.UpdateFallbackDomain(context.Background(), accountID, domainList)
_, err := client.UpdateFallbackDomain(context.Background(), accountID, getDefaultDomains())
if err != nil {
return err
}
Expand Down Expand Up @@ -138,30 +125,11 @@ func expandFallbackDomains(domains []interface{}) []cloudflare.FallbackDomain {
func getDefaultDomains() []cloudflare.FallbackDomain {
domainList := make([]cloudflare.FallbackDomain, 0)

for _, domain := range default_domains() {
for _, domain := range default_domains {
domainList = append(domainList, cloudflare.FallbackDomain{
Suffix: domain,
})
}

return domainList
}

func resourceCloudflareFallbackDomainDiff(_ context.Context, diff *schema.ResourceDiff, meta interface{}) error {
_, include_n := diff.GetChange("include_default_domains")
_, domains_n := diff.GetChange("domains")
domains_y := domains_n.([]interface{})

var domainList []interface{}
if include_n.(bool) {
domainList = flattenFallbackDomains(getDefaultDomains())
}
for _, domain := range domains_y {
domainList = append(domainList, domain.(map[string]interface{}))
}
if err := diff.SetNew("domains", domainList); err != nil {
return fmt.Errorf("error including default domains: %w", err)
}

return nil
}
89 changes: 16 additions & 73 deletions cloudflare/resource_cloudflare_fallback_domain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccCloudflareFallbackDomain_no_restore_on_delete(t *testing.T) {
func TestAccCloudflareFallbackDomain(t *testing.T) {
// Temporarily unset CLOUDFLARE_API_TOKEN if it is set as the Access
// service does not yet support the API tokens and it results in
// misleading state error messages.
Expand All @@ -24,63 +24,16 @@ func TestAccCloudflareFallbackDomain_no_restore_on_delete(t *testing.T) {

rnd := generateRandomResourceName()
name := fmt.Sprintf("cloudflare_fallback_domain.%s", rnd)
default_domain_count := len(default_domains())

resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccessAccPreCheck(t)
},
Providers: testAccProviders,
CheckDestroy: testAccCheckCloudflareFallbackDomainDestroy,
Steps: []resource.TestStep{
{
Config: testAccCloudflareFallbackDomain(rnd, accountID, "false", "false", "example domain", "example.com", "2.2.2.2"),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(name, "account_id", accountID),
resource.TestCheckResourceAttr(name, "domains.#", "1"),
resource.TestCheckResourceAttr(name, "domains.0.description", "example domain"),
resource.TestCheckResourceAttr(name, "domains.0.suffix", "example.com"),
resource.TestCheckResourceAttr(name, "domains.0.dns_server.0", "2.2.2.2"),
),
},
{
Config: testAccCloudflareFallbackDomain(rnd, accountID, "true", "false", "second example domain", "example_two.com", "1.1.1.1"),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(name, "account_id", accountID),
resource.TestCheckResourceAttr(name, "domains.#", fmt.Sprintf("%d", default_domain_count+1)),
resource.TestCheckResourceAttr(name, fmt.Sprintf("domains.%d.description", default_domain_count), "second example domain"),
resource.TestCheckResourceAttr(name, fmt.Sprintf("domains.%d.suffix", default_domain_count), "example_two.com"),
resource.TestCheckResourceAttr(name, fmt.Sprintf("domains.%d.dns_server.0", default_domain_count), "1.1.1.1"),
),
},
},
})
}

func TestAccCloudflareFallbackDomain_with_restore_on_delete(t *testing.T) {
// Temporarily unset CLOUDFLARE_API_TOKEN if it is set as the Access
// service does not yet support the API tokens and it results in
// misleading state error messages.
if os.Getenv("CLOUDFLARE_API_TOKEN") != "" {
defer func(apiToken string) {
os.Setenv("CLOUDFLARE_API_TOKEN", apiToken)
}(os.Getenv("CLOUDFLARE_API_TOKEN"))
os.Setenv("CLOUDFLARE_API_TOKEN", "")
}

rnd := generateRandomResourceName()
name := fmt.Sprintf("cloudflare_fallback_domain.%s", rnd)
default_domain_count := len(default_domains())

resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccessAccPreCheck(t)
},
Providers: testAccProviders,
CheckDestroy: testAccCheckCloudflareFallbackDomainDestroy,
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccCloudflareFallbackDomain(rnd, accountID, "false", "true", "example domain", "example.com", "2.2.2.2"),
Config: testAccCloudflareFallbackDomain(rnd, accountID, "example domain", "example.com", "2.2.2.2"),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(name, "account_id", accountID),
resource.TestCheckResourceAttr(name, "domains.#", "1"),
Expand All @@ -90,33 +43,30 @@ func TestAccCloudflareFallbackDomain_with_restore_on_delete(t *testing.T) {
),
},
{
// test only changing `include_default_domains`
Config: testAccCloudflareFallbackDomain(rnd, accountID, "true", "true", "example domain", "example.com", "2.2.2.2"),
Config: testAccCloudflareFallbackDomain(rnd, accountID, "second example domain", "example_two.com", "1.1.1.1"),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(name, "account_id", accountID),
resource.TestCheckResourceAttr(name, "domains.#", fmt.Sprintf("%d", default_domain_count+1)),
resource.TestCheckResourceAttr(name, fmt.Sprintf("domains.%d.description", default_domain_count), "example domain"),
resource.TestCheckResourceAttr(name, fmt.Sprintf("domains.%d.suffix", default_domain_count), "example.com"),
resource.TestCheckResourceAttr(name, fmt.Sprintf("domains.%d.dns_server.0", default_domain_count), "2.2.2.2"),
resource.TestCheckResourceAttr(name, "domains.#", "1"),
resource.TestCheckResourceAttr(name, "domains.0.description", "second example domain"),
resource.TestCheckResourceAttr(name, "domains.0.suffix", "example_two.com"),
resource.TestCheckResourceAttr(name, "domains.0.dns_server.0", "1.1.1.1"),
),
},
},
})
}

func testAccCloudflareFallbackDomain(rnd, accountID string, include_default string, restore_on_delete string, description string, suffix string, dns_server string) string {
func testAccCloudflareFallbackDomain(rnd, accountID string, description string, suffix string, dns_server string) string {
return fmt.Sprintf(`
resource "cloudflare_fallback_domain" "%[1]s" {
account_id = "%[2]s"
include_default_domains = %[3]s
restore_default_domains_on_delete = %[4]s
account_id = "%[2]s"
domains {
description = "%[5]s"
suffix = "%[6]s"
dns_server = ["%[7]s"]
description = "%[3]s"
suffix = "%[4]s"
dns_server = ["%[5]s"]
}
}
`, rnd, accountID, include_default, restore_on_delete, description, suffix, dns_server)
`, rnd, accountID, description, suffix, dns_server)
}

func testAccCheckCloudflareFallbackDomainDestroy(s *terraform.State) error {
Expand All @@ -128,15 +78,8 @@ func testAccCheckCloudflareFallbackDomainDestroy(s *terraform.State) error {
}

result, _ := client.ListFallbackDomains(context.Background(), rs.Primary.ID)
if rs.Primary.Attributes["restore_default_domains_on_delete"] == "true" {
default_domain_count := len(default_domains())
if len(result) != default_domain_count {
return fmt.Errorf("Deleted Fallback Domains resource has %d domains instead of expected %d default entries.", len(result), default_domain_count)
}
} else {
if len(result) > 0 {
return fmt.Errorf("Deleted Fallback Domains resource has %d domains, but should be empty.", len(result))
}
if len(result) != len(default_domains) {
return fmt.Errorf("Deleted Fallback Domains resource has %d domains instead of expected %d default entries.", len(result), len(default_domains))
}
}

Expand Down
19 changes: 2 additions & 17 deletions cloudflare/schema_cloudflare_fallback_domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,14 @@ func resourceCloudflareFallbackDomainSchema() map[string]*schema.Schema {
Type: schema.TypeString,
Required: true,
},
"include_default_domains": {
Optional: true,
Type: schema.TypeBool,
Default: false,
},
"restore_default_domains_on_delete": {
Optional: true,
Type: schema.TypeBool,
Default: true,
},
// `domains` should really be a schema.TypeSet, but there's an SDK bug that breaks
// default domain support. `dns_servers` ends up as a list of `nil` values in
// the ResourceDiff GetChange() result.
// See: https://github.com/hashicorp/terraform-plugin-sdk/issues/497
"domains": {
Optional: true,
Computed: true,
Required: true,
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"suffix": {
Type: schema.TypeString,
Required: true,
Optional: true,
Description: "The domain suffix to match when resolving locally.",
},
"description": {
Expand Down
26 changes: 3 additions & 23 deletions website/docs/r/fallback_domain.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,9 @@ Provides a Cloudflare Fallback Domain resource. Fallback domains are used to ign
## Example Usage

```hcl
# Adding example.com to the default fallback domain list.
# Upon resource deletion, restore the default entries.
resource "cloudflare_fallback_domain" "with_defaults" {
account_id = "1d5fdc9e88c8a8c4518b068cd94331fe"
include_default_domains = true
restore_default_domains_on_delete = true
domains {
suffix = "example.com"
description = "Example domain"
dns_server = ["1.1.1.1", "2.2.2.2"]
}
}
```

```hcl
# Specify all domains explicitly, including default domains.
# Upon deletion, leave domains empty.
resource "cloudflare_fallback_domain" "explicit" {
account_id = "1d5fdc9e88c8a8c4518b068cd94331fe"
include_default_domains = false
restore_default_domains_on_delete = false
# Explicitly adding example.com to the default entries.
resource "cloudflare_fallback_domain" "example" {
account_id = "1d5fdc9e88c8a8c4518b068cd94331fe"
dynamic "domains" {
for_each = toset(["intranet", "internal", "private", "localdomain", "domain", "lan", "home", "host", "corp", "local", "localhost", "home.arpa", "invalid", "test"])
content {
Expand All @@ -55,8 +37,6 @@ The following arguments are supported:

- `account_id` - (Required) The account to which the device posture rule should be added.
- `domains` - (Required) The value of the domain attributes (refer to the [nested schema](#nestedblock--domains)).
- `include_default_domains` - (Optional) Indicator to include default domains (shown in `explicit` example) to specified list of domains. Defaults to `false`.
- `restore_default_domains_on_delete` - (Optional) Indicator to reset domains to default list upon delete. Otherwise, list will be empty. Defaults to `true`.

<a id="nestedblock--domains"></a>
**Nested schema for `domains`**
Expand Down

0 comments on commit 2fb0985

Please sign in to comment.