Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Hostnames Resource #580

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cloudflare/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ func Provider() terraform.ResourceProvider {
"cloudflare_access_service_token": resourceCloudflareAccessServiceToken(),
"cloudflare_account_member": resourceCloudflareAccountMember(),
"cloudflare_argo": resourceCloudflareArgo(),
"cloudflare_custom_hostnames": resourceCloudflareCustomHostnames(),
"cloudflare_custom_pages": resourceCloudflareCustomPages(),
"cloudflare_custom_ssl": resourceCloudflareCustomSsl(),
"cloudflare_filter": resourceCloudflareFilter(),
Expand Down
223 changes: 223 additions & 0 deletions cloudflare/resource_cloudflare_custom_hostnames.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
package cloudflare

import (
"fmt"
"log"
"strings"

"github.com/hashicorp/terraform-plugin-sdk/helper/validation"

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

func resourceCloudflareCustomHostnames() *schema.Resource {
return &schema.Resource{
Create: resourceCloudflareCustomHostnamesCreate,
Read: resourceCloudflareCustomHostnamesRead,
Update: resourceCloudflareCustomHostnamesUpdate,
Delete: resourceCloudflareCustomHostnamesDelete,
Importer: &schema.ResourceImporter{
State: resourceCloudflareCustomHostnamesImport,
},

Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Required: true,
},

"hostname": {
Type: schema.TypeString,
Required: true,
},
"custom_origin_server": {
Type: schema.TypeString,
Optional: true,
},
"ssl": {
Type: schema.TypeList,
Required: true,
MinItems: 1,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Computed: true,
},
"method": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"http", "email", "cname"}, false),
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"dv"}, false),
},
"custom_hostname_settings": {
Type: schema.TypeList,
MaxItems: 4,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"http2": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
},
"tls13": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
},
"mintlsversion": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"1.0", "1.1", "1.2", "1.3"}, false),
},
"ciphers": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
},
},
},
},
}
}

func resourceCloudflareCustomHostnamesCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cloudflare.API)
zoneID := d.Get("zone_id").(string)
log.Printf("[DEBUG] zone ID: %s", zoneID)
zcso := expandToZoneCustomHostnamesOptions(d)
res, err := client.CreateCustomHostname(zoneID, zcso)
if err != nil {
return fmt.Errorf("Failed to create custom hostname cert: %s", err)
}

if res.Result.ID == "" {
return fmt.Errorf("Failed to find custom ssl in Create response: id was empty")
}

d.SetId(res.Result.ID)

log.Printf("[INFO] Cloudflare Custom SSL ID: %s", d.Id())

return resourceCloudflareCustomHostnamesRead(d, meta)
}

func resourceCloudflareCustomHostnamesUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cloudflare.API)
zoneID := d.Get("zone_id").(string)
certID := d.Id()
zcso := expandToZoneCustomHostnamesOptionsSSL(d)

log.Printf("[INFO] Updating Custom Hostname from struct: %+v", zcso)

_, err := client.UpdateCustomHostnameSSL(zoneID, certID, zcso)
if err != nil {
return errors.Wrap(err, "Error updating Custom Hostname")
}

return resourceCloudflareCustomHostnamesRead(d, meta)
}

func resourceCloudflareCustomHostnamesRead(d *schema.ResourceData, meta interface{}) error {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why aren't the ssl option changes reflected in the Read? If the remote changes them for any reason, it's not reflected here.

client := meta.(*cloudflare.API)
zoneID := d.Get("zone_id").(string)
certID := d.Id()

// update all possible schema attributes with fields from api response
record, err := client.CustomHostname(zoneID, certID)
if err != nil {
log.Printf("[WARN] Removing record from state because it's not found in API")
d.SetId("")
return nil
}
d.Set("hostname", record.Hostname)
d.Set("custom_origin_server", record.CustomOriginServer)
return nil
}

func resourceCloudflareCustomHostnamesDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cloudflare.API)
zoneID := d.Get("zone_id").(string)
certID := d.Id()

log.Printf("[DEBUG] Deleting Custom Hostname cert %s for zone %s", certID, zoneID)

err := client.DeleteCustomHostname(zoneID, certID)
if err != nil {
errors.Wrap(err, "failed to delete custom hostanme cert setting")
}
return nil
}

func resourceCloudflareCustomHostnamesImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
// split the id so we can lookup
idAttr := strings.SplitN(d.Id(), "/", 2)
if len(idAttr) != 2 {
return nil, fmt.Errorf("invalid id (\"%s\") specified, should be in format \"zoneID/certID\"", d.Id())
}

zoneID, certID := idAttr[0], idAttr[1]

log.Printf("[DEBUG] Importing Cloudflare Custom SSL Cert: id %s for zone %s", certID, zoneID)

d.Set("zone_id", zoneID)
d.SetId(certID)

resourceCloudflareCustomHostnamesRead(d, meta)

return []*schema.ResourceData{d}, nil
}

func expandToZoneCustomHostnamesOptions(d *schema.ResourceData) (options cloudflare.CustomHostname) {

options = cloudflare.CustomHostname{
Hostname: d.Get("hostname").(string),
CustomOriginServer: d.Get("custom_origin_server").(string),
}

options.SSL = expandToZoneCustomHostnamesOptionsSSL(d)

return options
}

func expandToZoneCustomHostnamesOptionsSSL(d *schema.ResourceData) (options cloudflare.CustomHostnameSSL) {
v, ok := d.GetOk("ssl")
if !ok {
return
}
cfg := v.([]interface{})[0].(map[string]interface{})

sslOpt := cloudflare.CustomHostnameSSL{
Method: cfg["method"].(string),
Type: cfg["type"].(string),
Status: cfg["status"].(string),
}

if hostSettIface, ok := cfg["custom_hostname_settings"]; ok && len(hostSettIface.([]interface{})) > 0 {
hostSett := hostSettIface.([]interface{})[0].(map[string]interface{})

hostOptions := cloudflare.CustomHostnameSSLSettings{
HTTP2: hostSett["http2"].(string),
TLS13: hostSett["tls13"].(string),
MinTLSVersion: hostSett["mintlsversion"].(string),
Ciphers: expandInterfaceToStringList(hostSett["ciphers"]),
}
sslOpt.Settings = hostOptions
}
return sslOpt
}
146 changes: 146 additions & 0 deletions cloudflare/resource_cloudflare_custom_hostnames_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
package cloudflare

import (
"fmt"
"os"
"testing"

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

func TestAccCloudflareCustomHostname_Basic(t *testing.T) {
t.Parallel()
var customHostname cloudflare.CustomHostname
zoneID := os.Getenv("CLOUDFLARE_ZONE_ID")
rnd := generateRandomResourceName()
resourceName := "cloudflare_custom_hostname." + rnd
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckCloudflareCustomHostnameDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckCloudflareCustomHostnameBasic(zoneID, rnd),
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudflareCustomHostnameExists(resourceName, &customHostname),
resource.TestCheckResourceAttr(
resourceName, "zone_id", zoneID),
resource.TestCheckResourceAttr(
resourceName, "hostname", "thisis@cool.com"),
resource.TestCheckResourceAttr(
resourceName, "ssl.method", "http"),
),
},
},
})
}

func TestAccCloudflareCustomHostname_Advanced(t *testing.T) {
t.Parallel()
var customHostname cloudflare.CustomHostname
zoneID := os.Getenv("CLOUDFLARE_ZONE_ID")
rnd := generateRandomResourceName()
resourceName := "cloudflare_custom_hostname." + rnd
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckCloudflareCustomHostnameDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckCloudflareCustomHostnameAdvanced(zoneID, rnd),
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudflareCustomHostnameExists(resourceName, &customHostname),
resource.TestCheckResourceAttr(
resourceName, "zone_id", zoneID),
resource.TestCheckResourceAttr(
resourceName, "custom_origin_server", "serverone.myinfra.com"),
resource.TestCheckResourceAttr(
resourceName, "ssl.method", "http"),
resource.TestCheckResourceAttr(
resourceName, "hostname", "thisis@cool.com"),
resource.TestCheckResourceAttr(
resourceName, "ssl.custom_hostname_settings.tls13", "on"),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you run these integration tests? A TypeList is sequentially indice based which means these nested values should have an index in front of them.

resource.TestCheckResourceAttr(
resourceName, "ssl.custom_hostname_settings.http2", "on"),
resource.TestCheckResourceAttr(
resourceName, "ssl.custom_hostname_settings.mintlsversion", "1.1"),
),
},
},
})
}

func testAccCheckCloudflareCustomHostnameBasic(zoneID string, rName string) string {
return fmt.Sprintf(`
resource "cloudflare_custom_hostname" "%[2]s" {
zone_id = "%[1]s"
hostname = "thisis@cool.com"
ssl = {
method = "http"
}
}`, zoneID, rName)
}

func testAccCheckCloudflareCustomHostnameAdvanced(zoneID string, rName string) string {
return fmt.Sprintf(`
resource "cloudflare_custom_hostname" "%[2]s" {
zone_id = "%[1]s"
hostname = "thisis@cool.com"
custom_origin_server = "serverone.myinfra.com"
ssl {
method = "http"
custom_hostname_settings {
http2 = "on"
tls13 = "on"
mintlsversion = "1.1"
ciphers = ["ECDHE-RSA-AES128-GCM-SHA256","AES128-SHA"]
}
}
}`, zoneID, rName)
}

func testAccCheckCloudflareCustomHostnameDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*cloudflare.API)

for _, rs := range s.RootModule().Resources {
if rs.Type != "cloudflare_custom_hostname" {
continue
}

err := client.DeleteCustomHostname(rs.Primary.Attributes["zone_id"], rs.Primary.ID)
if err == nil {
return fmt.Errorf("custom hostname still exists")
}
}

return nil
}

func testAccCheckCloudflareCustomHostnameExists(n string, customHostname *cloudflare.CustomHostname) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}

if rs.Primary.ID == "" {
return fmt.Errorf("No cert ID is set")
}

client := testAccProvider.Meta().(*cloudflare.API)
foundCustomHostname, err := client.CustomHostname(rs.Primary.Attributes["zone_id"], rs.Primary.ID)
if err != nil {
return err
}

if foundCustomHostname.ID != rs.Primary.ID {
return fmt.Errorf("cert not found")
}

*customHostname = foundCustomHostname

return nil
}
}