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

implement custom ssl resource #418

Merged
merged 20 commits into from
Aug 5, 2019
Merged
Show file tree
Hide file tree
Changes from 7 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 @@ -95,6 +95,7 @@ func Provider() terraform.ResourceProvider {
"cloudflare_account_member": resourceCloudflareAccountMember(),
"cloudflare_argo": resourceCloudflareArgo(),
"cloudflare_custom_pages": resourceCloudflareCustomPages(),
"cloudflare_custom_ssl": resourceCloudflareCustomSsl(),
"cloudflare_filter": resourceCloudflareFilter(),
"cloudflare_firewall_rule": resourceCloudflareFirewallRule(),
"cloudflare_load_balancer_monitor": resourceCloudflareLoadBalancerMonitor(),
Expand Down
295 changes: 295 additions & 0 deletions cloudflare/resource_cloudflare_custom_ssl.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
package cloudflare

import (
"encoding/json"
"fmt"
"github.com/hashicorp/terraform/helper/validation"
"log"
"strings"
"time"

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

func resourceCloudflareCustomSsl() *schema.Resource {
return &schema.Resource{
Create: resourceCloudflareCustomSslCreate,
Read: resourceCloudflareCustomSslRead,
Update: resourceCloudflareCustomSslUpdate,
Delete: resourceCloudflareCustomSslDelete,
Importer: &schema.ResourceImporter{
State: resourceCloudflareCustomSslImport,
},

Schema: map[string]*schema.Schema{
Copy link
Member

Choose a reason for hiding this comment

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

We're missing some fields from the schema, is this intentional? The API shows the following also available:

  • type
  • geo_restrictions

Copy link
Contributor Author

Choose a reason for hiding this comment

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

These are not supported by v4api https://github.com/cloudflare/cloudflare-go/blob/master/ssl.go#L40-L44. Ill cut a PR against that repo and then update this one likely in a separate PR.

Copy link
Member

Choose a reason for hiding this comment

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

🙇 thanks for getting that updated! PR is at cloudflare/cloudflare-go#327

"zone_id": {
Type: schema.TypeString,
Required: true,
},
"custom_ssl_priority": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Optional: true,
},
"priority": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"custom_ssl_options": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"certificate": {
Type: schema.TypeString,
Optional: false,
},
"private_key": {
jacobbednarz marked this conversation as resolved.
Show resolved Hide resolved
Type: schema.TypeString,
Optional: false,
Sensitive: true,
},
"bundle_method": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ubiquitous", "optimal", "force"}, false),
},
"geo_restrictions": {
Type: schema.TypeMap,
Optional: true,
Copy link
Member

Choose a reason for hiding this comment

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

As the API has restrictions on what values can be used here, it's helpful to provide validation before the HTTP interactions are made.

Suggested change
Optional: true,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ubiquitous", "optimal", "force"}, false),

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was planning on adding validations as a separate ticket. This one establishes minimal functionality for creating, updating, deleting custom_ssl resource. I can add validation for requisite parameters on POST , PUT encapsulating functions though no problem.

Copy link
Member

Choose a reason for hiding this comment

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

Understandable. If we can, I prefer to have as much validation up front as (even with MVP style PRs) to speed up the feedback loop that users get. For example, our Terraform configuration is across ~40 domains and if we apply changes we can wait up to a couple of minutes for the payload to hit the Cloudflare API only to inform us that we've incorrectly formatted a field or gave it an unexpected value. Compared to schema based validation, we get that almost instantly. It does make the user UX quite a bit nicer and doesn't waste as much time on larger installs 🙂

Copy link
Contributor Author

@jterzis jterzis Jul 18, 2019

Choose a reason for hiding this comment

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

Forgot to update this after I added Validation for post fields that take on a set of string values, namely bundle_method, geo_restrictions, type.

Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"label": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"us", "eu", "highest_security"}, false),
},
},
},
},
"type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"legacy_custom", "sni_custom"}, false),
},
},
},
},
"hosts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"issuer": {
Type: schema.TypeString,
Computed: true,
},
"signature": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"uploaded_on": {
Type: schema.TypeString,
Computed: true,
},
"modified_on": {
Type: schema.TypeString,
Computed: true,
},
"expires_on": {
Type: schema.TypeString,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}

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

res, err := client.CreateSSL(zoneID, zcso)
if err != nil {
return fmt.Errorf("Failed to create custom ssl cert: %s", err)
}

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

d.SetId(res.ID)

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

return resourceCloudflareCustomSslRead(d, meta)
}

func resourceCloudflareCustomSslUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cloudflare.API)
zoneID := d.Get("zone_id").(string)
certID := d.Id()
log.Printf("[DEBUG] zone ID: %s", zoneID)

zcso, err := expandToZoneCustomSSLOptions(d)
if err != nil {
return fmt.Errorf("Failed to update custom ssl cert: %s", err)
}

res, err := client.UpdateSSL(zoneID, certID, zcso)
if err != nil {
fmt.Printf("Failed to update custom ssl cert: %s", err)
}

log.Printf("[DEBUG] Custom SSL set to: %s", res.ID)

zcsp, err := expandToZoneCustomSSLPriority(d)
if err != nil {
return fmt.Errorf("Failed to update custom ssl cert: %s", err)
}

resList, err := client.ReprioritizeSSL(zoneID, zcsp)
if err != nil {
return fmt.Errorf("Failed to update / reprioritize custom ssl cert: %s", err)
}
log.Printf("[DEBUG] Custom SSL reprioritized to: %#v", resList)

return resourceCloudflareCustomSslRead(d, meta)
}

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

record, err := client.SSLDetails(zoneID, certID)
if err != nil {
log.Printf("[WARN] Removing record from state because it's not found in API")
d.SetId("")
return nil
}

d.SetId(record.ID)
d.Set("hosts", record.Hosts)
d.Set("issuer", record.Issuer)
d.Set("signature", record.Signature)
d.Set("status", record.Status)
d.Set("uploaded_on", record.UploadedOn.Format(time.RFC3339Nano))
d.Set("expires_on", record.ExpiresOn.Format(time.RFC3339Nano))
d.Set("modified_on", record.ModifiedOn.Format(time.RFC3339Nano))
d.Set("priority", record.Priority)
return nil
}

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

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

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

func resourceCloudflareCustomSslImport(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)

resourceCloudflareCustomSslRead(d, meta)

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

func expandToZoneCustomSSLPriority(d *schema.ResourceData) ([]cloudflare.ZoneCustomSSLPriority, error) {
data, dataOk := d.GetOk("custom_ssl_priority")
log.Printf("[DEBUG] Custom SSL priority found in config: %#v", data)
var mtSlice []cloudflare.ZoneCustomSSLPriority
if dataOk {
Copy link
Member

Choose a reason for hiding this comment

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

Personal preference here (so take it or leave it 😛) but I'd look to return early here and instead of nesting another level as while it's not too big of a deal now, Go is pretty good at getting gnarly nested if expressions. I.e.

data, dataOk := d.GetOk("custom_ssl_priority")

// ..

if !dataOk {
    // Perhaps a better exception than `nil` but 🤷‍♂ 
    return mtSlice, nil
}

for _, innerData := range data.([]interface{}) { 
    newData := make(map[string]interface{})
    // .. continue on
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This appears to be more idiomatic so Ill take your suggestion, thanks!

for _, innerData := range data.([]interface{}) {
newData := make(map[string]interface{})
for id, value := range innerData.(map[string]interface{}) {
switch idName := id; idName {
case "id":
newValue := value.(string)
newData["ID"] = newValue
case "priority":
newValue := value.(int)
newData[id] = newValue
default:
newValue := value
newData[id] = newValue
}
}
zcsp := cloudflare.ZoneCustomSSLPriority{}
zcspJson, err := json.Marshal(newData)
if err != nil {
return mtSlice, fmt.Errorf("Failed to create custom ssl priorities: %s", err)
}
// map -> json -> struct
json.Unmarshal(zcspJson, &zcsp)
mtSlice = append(mtSlice, zcsp)
}
}
log.Printf("[DEBUG] Custom SSL priority list creating: %#v", mtSlice)
return mtSlice, nil
}

func expandToZoneCustomSSLOptions(d *schema.ResourceData) (cloudflare.ZoneCustomSSLOptions, error) {
data, dataOk := d.GetOk("custom_ssl_options")
log.Printf("[DEBUG] Custom SSL options found in config: %#v", data)

newData := make(map[string]string)
if dataOk {
for id, value := range data.(map[string]interface{}) {
newValue := value.(string)
newData[id] = newValue
}
}

zcso := cloudflare.ZoneCustomSSLOptions{}
zcsoJson, err := json.Marshal(newData)
if err != nil {
return zcso, fmt.Errorf("Failed to create custom ssl options: %s", err)
}
// map -> json -> struct
json.Unmarshal(zcsoJson, &zcso)
log.Printf("[DEBUG] Custom SSL options creating: %#v", zcso)
return zcso, nil
}
Loading