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

Revathy/add webhooks resource #1151

Merged
Merged
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 @@ -158,6 +158,7 @@ func Provider() terraform.ResourceProvider {
"cloudflare_zone": resourceCloudflareZone(),
"cloudflare_zone_dnssec": resourceCloudflareZoneDNSSEC(),
"cloudflare_notification_policy": resourceCloudflareNotificationPolicy(),
"cloudflare_notification_policy_webhooks": resourceCloudflareNotificationPolicyWebhooks(),
},
}

Expand Down
171 changes: 171 additions & 0 deletions cloudflare/resource_cloudflare_notification_policy_webhooks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
package cloudflare

import (
"context"
"fmt"
"strings"
"time"

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

func resourceCloudflareNotificationPolicyWebhooks() *schema.Resource {
return &schema.Resource{
Create: resourceCloudflareNotificationPolicyWebhooksCreate,
Read: resourceCloudflareNotificationPolicyWebhooksRead,
Update: resourceCloudflareNotificationPolicyWebhooksUpdate,
Delete: resourceCloudflareNotificationPolicyWebhooksDelete,
Importer: &schema.ResourceImporter{
State: resourceCloudflareNotificationPolicyWebhooksImport,
},

Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Required: true,
},
"name": {
Type: schema.TypeString,
Required: true,
},
"url": {
Type: schema.TypeString,
Optional: true,
},
"secret": {
Type: schema.TypeString,
Optional: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"created_at": {
Type: schema.TypeString,
Computed: true,
},
"last_success": {
Type: schema.TypeString,
Computed: true,
},
"last_failure": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func resourceCloudflareNotificationPolicyWebhooksCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cloudflare.API)
accountID := d.Get("account_id").(string)

notificationWebhooks := buildNotificationPolicyWebhooks(d)

webhooksDestination, err := client.CreateNotificationWebhooks(context.Background(), accountID, &notificationWebhooks)

if err != nil {
return fmt.Errorf("error connecting webhooks destination %s: %s", notificationWebhooks.Name, err)
}
formattedWebhookID, err := uuid.Parse(webhooksDestination.Result.ID)
if err != nil {
return fmt.Errorf("error setting notification webhooks: %s", err)
}

d.SetId(formattedWebhookID.String())

return resourceCloudflareNotificationPolicyWebhooksRead(d, meta)
}

func resourceCloudflareNotificationPolicyWebhooksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cloudflare.API)
webhooksDestinationID := d.Id()
accountID := d.Get("account_id").(string)

notificationWebhooks, err := client.GetNotificationWebhooks(context.Background(), accountID, webhooksDestinationID)

name := d.Get("name").(string)
if err != nil {
return fmt.Errorf("error retrieving notification webhooks %s: %s", name, err)
}

d.Set("name", notificationWebhooks.Result.Name)
d.Set("url", notificationWebhooks.Result.URL)
d.Set("created", notificationWebhooks.Result.CreatedAt.Format(time.RFC3339))
d.Set("type", notificationWebhooks.Result.Type)

if notificationWebhooks.Result.LastSuccess != nil {
d.Set("last_success", notificationWebhooks.Result.LastSuccess.Format(time.RFC3339))
}
if notificationWebhooks.Result.LastFailure != nil {
d.Set("last_failure", notificationWebhooks.Result.LastFailure.Format(time.RFC3339))
}

return nil
}

func resourceCloudflareNotificationPolicyWebhooksUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cloudflare.API)
webhooksID := d.Id()
accountID := d.Get("account_id").(string)

notificationWebhooks := buildNotificationPolicyWebhooks(d)

_, err := client.UpdateNotificationWebhooks(context.Background(), accountID, webhooksID, &notificationWebhooks)

if err != nil {
return fmt.Errorf("error updating notification webhooks destination %s: %s", webhooksID, err)
}

return resourceCloudflareNotificationPolicyWebhooksRead(d, meta)
}

func resourceCloudflareNotificationPolicyWebhooksDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cloudflare.API)
webhooksID := d.Id()
accountID := d.Get("account_id").(string)

_, err := client.DeleteNotificationWebhooks(context.Background(), accountID, webhooksID)

if err != nil {
return fmt.Errorf("error deleting notification webhooks destination %s: %s", webhooksID, err)
}
return nil
}

func resourceCloudflareNotificationPolicyWebhooksImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
attributes := strings.SplitN(d.Id(), "/", 2)

if len(attributes) != 2 {
return nil, fmt.Errorf("invalid id (\"%s\") specified, should be in format \"accountID/webhooksID\"", d.Id())
}

accountID, webhooksID := attributes[0], attributes[1]
d.SetId(webhooksID)
d.Set("account_id", accountID)

resourceCloudflareNotificationPolicyWebhooksRead(d, meta)

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

}

func buildNotificationPolicyWebhooks(d *schema.ResourceData) cloudflare.NotificationUpsertWebhooks {
webhooks := cloudflare.NotificationUpsertWebhooks{}

if name, ok := d.GetOk("name"); ok {
webhooks.Name = name.(string)
}

if url, ok := d.GetOk("url"); ok {
webhooks.URL = url.(string)
}

if secret, ok := d.GetOk("secret"); ok {
webhooks.Secret = secret.(string)
}

return webhooks
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package cloudflare

import (
"fmt"
"os"
"testing"

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

func TestAccCloudflareNotificationPolicyWebhooks(t *testing.T) {
Copy link
Member

Choose a reason for hiding this comment

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

acceptance tests are 🍏

==> Checking that code complies with gofmt requirements...
TF_ACC=1 go test $(go list ./...) -v -run "^TestAccCloudflareNotificationPolicyWebhooks" -timeout 120m -parallel 1
?   	github.com/cloudflare/terraform-provider-cloudflare	[no test files]
=== RUN   TestAccCloudflareNotificationPolicyWebhooks
--- PASS: TestAccCloudflareNotificationPolicyWebhooks (9.56s)
PASS
ok  	github.com/cloudflare/terraform-provider-cloudflare/cloudflare	10.261s
?   	github.com/cloudflare/terraform-provider-cloudflare/version	[no test files]

rnd := generateRandomResourceName()
resourceName := "cloudflare_notification_policy_webhooks." + rnd
webhooksDestination := "https://example.com"
updatedWebhooksName := "my updated webhooks destination for notifications"
accountID := os.Getenv("CLOUDFLARE_ACCOUNT_ID")

resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheckAccount(t)
},
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testCheckCloudflareNotificationPolicyWebhooks(rnd, accountID),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(resourceName, "name", "my webhooks destination for receiving Cloudflare notifications"),
resource.TestCheckResourceAttr(resourceName, "url", webhooksDestination),
),
},
{
Config: testCheckCloudflareNotificationPolicyWebhooksUpdated(rnd, updatedWebhooksName, accountID),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(resourceName, "name", updatedWebhooksName),
resource.TestCheckResourceAttr(resourceName, "url", webhooksDestination),
resource.TestCheckResourceAttr(resourceName, "type", "generic"),
),
},
},
})
}

func testCheckCloudflareNotificationPolicyWebhooks(name, accountID string) string {
return fmt.Sprintf(`
resource "cloudflare_notification_policy_webhooks" "%[1]s" {
account_id = "%[2]s"
name = "my webhooks destination for receiving Cloudflare notifications"
url = "https://example.com"
secret = "my-secret-key"
}`, name, accountID)
}

func testCheckCloudflareNotificationPolicyWebhooksUpdated(resName, webhooksName, accountID string) string {
return fmt.Sprintf(`
resource "cloudflare_notification_policy_webhooks" "%[1]s" {
account_id = "%[3]s"
name = "%[2]s"
url = "https://example.com"
}`, resName, webhooksName, accountID)
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.15

require (
github.com/cloudflare/cloudflare-go v0.20.0
github.com/google/uuid v1.1.2
github.com/hashicorp/go-cleanhttp v0.5.2
github.com/hashicorp/terraform-plugin-sdk v1.17.2
github.com/pkg/errors v0.9.1
Expand Down
40 changes: 40 additions & 0 deletions website/docs/r/notification_policy_webhooks.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
layout: "cloudflare"
page_title: "Cloudflare: cloudflare_notification_policy_webhooks"
sidebar_current: "docs-cloudflare-notification_policy_webhooks"
description: |-
Provides a resource to create and manage webhooks destinations for Cloudflare's notification policies.
---

# cloudflare_notification_policy_webhooks

Provides a resource, that manages a webhook destination. These destinations can be tied to the notification policies created for Cloudflare's products.

## Example Usage

```hcl
resource "cloudflare_notification_policy_webhooks" "example" {
account_id = "c4a7362d577a6c3019a474fd6f485821"
name = "Webhooks destination"
url = "https://example.com"
secret = "my-secret"
}
```

## Argument Reference

The following arguments are supported:
* `account_id` - (Required) The ID of the account for which the webhook destination has to be connected.
* `name` - (Required) The name of the webhook destination.
* `url` - (Required) The URL of the webhook destinations.
* `secret` - (Optional) An optional secret can be provided that will be passed in the `cf-webhook-auth` header when dispatching a webhook notification.
Secrets are not returned in any API response body.
Refer to the documentation for more details - https://api.cloudflare.com/#notification-webhooks-create-webhook.

## Import

An existing notification policy can be imported using the account ID and the webhook ID

```
$ terraform import cloudflare_notification_policy_webhooks.example 72c379d136459405d964d27aa0f18605/c4a7362d577a6c3019a474fd6f485821
```