From 7a35a4e2078cefea1418b698842e5bca36abecaa Mon Sep 17 00:00:00 2001 From: shuheiktgw Date: Sun, 14 Mar 2021 20:41:22 +0900 Subject: [PATCH 1/6] Add aws_cloudfront_monitoring_subscription resource --- .../service/cloudfront/finder/finder.go | 19 ++ aws/provider.go | 1 + ..._aws_cloudfront_monitoring_subscription.go | 165 ++++++++++++++++++ 3 files changed, 185 insertions(+) create mode 100644 aws/resource_aws_cloudfront_monitoring_subscription.go diff --git a/aws/internal/service/cloudfront/finder/finder.go b/aws/internal/service/cloudfront/finder/finder.go index 3741c1640bb..3f6a532602e 100644 --- a/aws/internal/service/cloudfront/finder/finder.go +++ b/aws/internal/service/cloudfront/finder/finder.go @@ -54,3 +54,22 @@ func RealtimeLogConfigByARN(conn *cloudfront.CloudFront, arn string) (*cloudfron return output.RealtimeLogConfig, nil } + +// MonitoringSubscriptionByDistributionId returns the monitoring subscription corresponding to the specified distribution id. +// Returns nil if no subscription is found. +func MonitoringSubscriptionByDistributionId(conn *cloudfront.CloudFront, id string) (*cloudfront.MonitoringSubscription, error) { + input := &cloudfront.GetMonitoringSubscriptionInput{ + DistributionId: aws.String(id), + } + + output, err := conn.GetMonitoringSubscription(input) + if err != nil { + return nil, err + } + + if output == nil { + return nil, nil + } + + return output.MonitoringSubscription, nil +} diff --git a/aws/provider.go b/aws/provider.go index bb29044942d..001ea6ce0ed 100644 --- a/aws/provider.go +++ b/aws/provider.go @@ -547,6 +547,7 @@ func Provider() *schema.Provider { "aws_cloudfront_distribution": resourceAwsCloudFrontDistribution(), "aws_cloudfront_function": resourceAwsCloudFrontFunction(), "aws_cloudfront_key_group": resourceAwsCloudFrontKeyGroup(), + "aws_cloudfront_monitoring_subscription": resourceAwsCloudFrontMonitoringSubscription(), "aws_cloudfront_origin_access_identity": resourceAwsCloudFrontOriginAccessIdentity(), "aws_cloudfront_origin_request_policy": resourceAwsCloudFrontOriginRequestPolicy(), "aws_cloudfront_public_key": resourceAwsCloudFrontPublicKey(), diff --git a/aws/resource_aws_cloudfront_monitoring_subscription.go b/aws/resource_aws_cloudfront_monitoring_subscription.go new file mode 100644 index 00000000000..71664e4c3a5 --- /dev/null +++ b/aws/resource_aws_cloudfront_monitoring_subscription.go @@ -0,0 +1,165 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/cloudfront" + "github.com/hashicorp/aws-sdk-go-base/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/cloudfront/finder" +) + +func resourceAwsCloudFrontMonitoringSubscription() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsCloudFrontMonitoringSubscriptionCreate, + Read: resourceAwsCloudFrontMonitoringSubscriptionRead, + Delete: resourceAwsCloudFrontMonitoringSubscriptionDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "distribution_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "monitoring_subscription": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + MinItems: 1, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "realtime_metrics_subscription_config": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + MinItems: 1, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "realtime_metrics_subscription_status": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(cloudfront.RealtimeMetricsSubscriptionStatus_Values(), false), + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func resourceAwsCloudFrontMonitoringSubscriptionCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).cloudfrontconn + + id := d.Get("distribution_id").(string) + input := &cloudfront.CreateMonitoringSubscriptionInput{ + DistributionId: aws.String(id), + MonitoringSubscription: expandCloudFrontMonitoringSubscription(d.Get("monitoring_subscription").([]interface{})), + } + + log.Printf("[DEBUG] Creating CloudFront Monitoring Subscription: %s", input) + _, err := conn.CreateMonitoringSubscription(input) + + if err != nil { + return fmt.Errorf("error creating CloudFront Monitoring Subscription (%s): %w", id, err) + } + + d.SetId(id) + + return resourceAwsCloudFrontMonitoringSubscriptionRead(d, meta) +} + +func resourceAwsCloudFrontMonitoringSubscriptionRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).cloudfrontconn + + subscription, err := finder.MonitoringSubscriptionByDistributionId(conn, d.Id()) + + if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, cloudfront.ErrCodeNoSuchDistribution) { + log.Printf("[WARN] CloudFront Distribution (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("error reading CloudFront Monitoring Subscription (%s): %w", d.Id(), err) + } + + if subscription == nil { + if d.IsNewResource() { + return fmt.Errorf("error reading CloudFront Monitoring Subscription (%s): not found", d.Id()) + } + log.Printf("[WARN] CloudFront Monitoring Subscription (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + d.Set("distribution_id", d.Id()) + if err := d.Set("monitoring_subscription", flattenCloudFrontMonitoringSubscription(subscription)); err != nil { + return fmt.Errorf("error setting monitoring_subscription: %w", err) + } + + return nil +} + +func resourceAwsCloudFrontMonitoringSubscriptionDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).cloudfrontconn + + log.Printf("[DEBUG] Deleting CloudFront Monitoring Subscription (%s)", d.Id()) + _, err := conn.DeleteMonitoringSubscription(&cloudfront.DeleteMonitoringSubscriptionInput{ + DistributionId: aws.String(d.Id()), + }) + + if tfawserr.ErrCodeEquals(err, cloudfront.ErrCodeNoSuchDistribution) { + return nil + } + + if err != nil { + return fmt.Errorf("error deleting CloudFront Monitoring Subscription (%s): %w", d.Id(), err) + } + + return nil +} + +func expandCloudFrontMonitoringSubscription(vSubscription []interface{}) *cloudfront.MonitoringSubscription { + if len(vSubscription) == 0 || vSubscription[0] == nil { + return nil + } + + mSubscription := vSubscription[0].(map[string]interface{}) + + return &cloudfront.MonitoringSubscription{ + RealtimeMetricsSubscriptionConfig: expandCloudFrontRealtimeMetricsSubscriptionConfig(mSubscription["realtime_metrics_subscription_config"].([]interface{})), + } +} + +func expandCloudFrontRealtimeMetricsSubscriptionConfig(vConfig []interface{}) *cloudfront.RealtimeMetricsSubscriptionConfig { + if len(vConfig) == 0 || vConfig[0] == nil { + return nil + } + + mConfig := vConfig[0].(map[string]interface{}) + + return &cloudfront.RealtimeMetricsSubscriptionConfig{ + RealtimeMetricsSubscriptionStatus: aws.String(mConfig["realtime_metrics_subscription_status"].(string)), + } +} + +func flattenCloudFrontMonitoringSubscription(subscription *cloudfront.MonitoringSubscription) []interface{} { + return []interface{}{map[string]interface{}{"realtime_metrics_subscription_config": flattenCloudFrontRealtimeMetricsSubscriptionConfig(subscription.RealtimeMetricsSubscriptionConfig)}} +} + +func flattenCloudFrontRealtimeMetricsSubscriptionConfig(config *cloudfront.RealtimeMetricsSubscriptionConfig) []interface{} { + return []interface{}{map[string]interface{}{"realtime_metrics_subscription_status": config.RealtimeMetricsSubscriptionStatus}} +} From d99391f006848c38a67204fe4ac9f51a882f80a8 Mon Sep 17 00:00:00 2001 From: shuheiktgw Date: Sun, 14 Mar 2021 20:41:50 +0900 Subject: [PATCH 2/6] Add tests for aws_cloudfront_monitoring_subscription resource --- ...cloudfront_monitoring_subscription_test.go | 282 ++++++++++++++++++ 1 file changed, 282 insertions(+) create mode 100644 aws/resource_aws_cloudfront_monitoring_subscription_test.go diff --git a/aws/resource_aws_cloudfront_monitoring_subscription_test.go b/aws/resource_aws_cloudfront_monitoring_subscription_test.go new file mode 100644 index 00000000000..4397e9b7c48 --- /dev/null +++ b/aws/resource_aws_cloudfront_monitoring_subscription_test.go @@ -0,0 +1,282 @@ +package aws + +import ( + "fmt" + "log" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/cloudfront" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/cloudfront/finder" +) + +func init() { + resource.AddTestSweepers("aws_cloudfront_monitoring_subscription", &resource.Sweeper{ + Name: "aws_cloudfront_monitoring_subscription", + F: testSweepCloudFrontMonitoringSubscriptions, + }) +} + +func testSweepCloudFrontMonitoringSubscriptions(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %s", err) + } + conn := client.(*AWSClient).cloudfrontconn + var sweeperErrs *multierror.Error + + distributionSummaries := make([]*cloudfront.DistributionSummary, 0) + + input := &cloudfront.ListDistributionsInput{} + err = conn.ListDistributionsPages(input, func(page *cloudfront.ListDistributionsOutput, lastPage bool) bool { + distributionSummaries = append(distributionSummaries, page.DistributionList.Items...) + return !lastPage + }) + if err != nil { + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping CloudFront Monitoring Subscriptions sweep for %s: %s", region, err) + return nil + } + return fmt.Errorf("error listing CloudFront Distributions: %s", err) + } + + if len(distributionSummaries) == 0 { + log.Print("[DEBUG] No CloudFront Distributions found") + return nil + } + + for _, distributionSummary := range distributionSummaries { + + _, err := conn.GetMonitoringSubscription(&cloudfront.GetMonitoringSubscriptionInput{ + DistributionId: distributionSummary.Id, + }) + if err != nil { + return fmt.Errorf("error reading CloudFront Monitoring Subscription %s: %s", aws.StringValue(distributionSummary.Id), err) + } + + _, err = conn.DeleteMonitoringSubscription(&cloudfront.DeleteMonitoringSubscriptionInput{ + DistributionId: distributionSummary.Id, + }) + if err != nil { + return fmt.Errorf("error deleting CloudFront Monitoring Subscription %s: %s", aws.StringValue(distributionSummary.Id), err) + } + } + + return sweeperErrs.ErrorOrNil() +} + +func TestAccAWSCloudFrontMonitoringSubscription_basic(t *testing.T) { + var v cloudfront.MonitoringSubscription + resourceName := "aws_cloudfront_monitoring_subscription.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPartitionHasServicePreCheck(cloudfront.EndpointsID, t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckCloudFrontMonitoringSubscriptionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCloudFrontMonitoringSubscriptionConfig(), + Check: resource.ComposeTestCheckFunc( + testAccCheckCloudFrontMonitoringSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttrSet(resourceName, "distribution_id"), + resource.TestCheckResourceAttr(resourceName, "monitoring_subscription.#", "1"), + resource.TestCheckResourceAttr(resourceName, "monitoring_subscription.0.realtime_metrics_subscription_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "monitoring_subscription.0.realtime_metrics_subscription_config.0.realtime_metrics_subscription_status", "Enabled"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSCloudFrontMonitoringSubscription_disappears(t *testing.T) { + var v cloudfront.MonitoringSubscription + resourceName := "aws_cloudfront_monitoring_subscription.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPartitionHasServicePreCheck(cloudfront.EndpointsID, t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckCloudFrontMonitoringSubscriptionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCloudFrontMonitoringSubscriptionConfig(), + Check: resource.ComposeTestCheckFunc( + testAccCheckCloudFrontMonitoringSubscriptionExists(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsCloudFrontMonitoringSubscription(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAWSCloudFrontMonitoringSubscription_RealtimeMetricsSubscriptionConfig(t *testing.T) { + var v cloudfront.MonitoringSubscription + resourceName := "aws_cloudfront_monitoring_subscription.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPartitionHasServicePreCheck(cloudfront.EndpointsID, t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckCloudFrontMonitoringSubscriptionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCloudFrontMonitoringSubscriptionRealtimeMetricsSubscriptionConfigConfig("Enabled"), + Check: resource.ComposeTestCheckFunc( + testAccCheckCloudFrontMonitoringSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttrSet(resourceName, "distribution_id"), + resource.TestCheckResourceAttr(resourceName, "monitoring_subscription.#", "1"), + resource.TestCheckResourceAttr(resourceName, "monitoring_subscription.0.realtime_metrics_subscription_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "monitoring_subscription.0.realtime_metrics_subscription_config.0.realtime_metrics_subscription_status", "Enabled"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSCloudFrontMonitoringSubscriptionRealtimeMetricsSubscriptionConfigConfig("Disabled"), + Check: resource.ComposeTestCheckFunc( + testAccCheckCloudFrontMonitoringSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttrSet(resourceName, "distribution_id"), + resource.TestCheckResourceAttr(resourceName, "monitoring_subscription.#", "1"), + resource.TestCheckResourceAttr(resourceName, "monitoring_subscription.0.realtime_metrics_subscription_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "monitoring_subscription.0.realtime_metrics_subscription_config.0.realtime_metrics_subscription_status", "Disabled"), + ), + }, + }, + }) +} + +func testAccCheckCloudFrontMonitoringSubscriptionDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).cloudfrontconn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_cloudfront_monitoring_subscription" { + continue + } + + s, err := finder.MonitoringSubscriptionByDistributionId(conn, rs.Primary.ID) + + if isAWSErr(err, cloudfront.ErrCodeNoSuchDistribution, "") { + continue + } + if err != nil { + return err + } + if s != nil { + continue + } + return fmt.Errorf("CloudFront Monitoring Subscription still exists: %s", rs.Primary.ID) + } + + return nil +} + +func testAccCheckCloudFrontMonitoringSubscriptionExists(n string, v *cloudfront.MonitoringSubscription) 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 CloudFront Monitoring Subscription ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).cloudfrontconn + out, err := finder.MonitoringSubscriptionByDistributionId(conn, rs.Primary.ID) + if err != nil { + return err + } + + *v = *out + + return nil + } +} + +func testAccAWSCloudFrontMonitoringSubscriptionConfigBase() string { + return ` +resource "aws_cloudfront_distribution" "test" { + enabled = true + retain_on_delete = false + + default_cache_behavior { + allowed_methods = ["GET", "HEAD"] + cached_methods = ["GET", "HEAD"] + target_origin_id = "test" + viewer_protocol_policy = "allow-all" + + forwarded_values { + query_string = false + + cookies { + forward = "all" + } + } + } + + origin { + domain_name = "www.example.com" + origin_id = "test" + + custom_origin_config { + http_port = 80 + https_port = 443 + origin_protocol_policy = "https-only" + origin_ssl_protocols = ["TLSv1.2"] + } + } + + restrictions { + geo_restriction { + restriction_type = "none" + } + } + + viewer_certificate { + cloudfront_default_certificate = true + } +} +` +} + +func testAccAWSCloudFrontMonitoringSubscriptionConfig() string { + return composeConfig( + testAccAWSCloudFrontMonitoringSubscriptionConfigBase(), + ` +resource "aws_cloudfront_monitoring_subscription" "test" { + distribution_id = aws_cloudfront_distribution.test.id + + monitoring_subscription { + realtime_metrics_subscription_config { + realtime_metrics_subscription_status = "Enabled" + } + } +} +`) +} + +func testAccAWSCloudFrontMonitoringSubscriptionRealtimeMetricsSubscriptionConfigConfig(status string) string { + return composeConfig( + testAccAWSCloudFrontMonitoringSubscriptionConfigBase(), + fmt.Sprintf(` +resource "aws_cloudfront_monitoring_subscription" "test" { + distribution_id = aws_cloudfront_distribution.test.id + + monitoring_subscription { + realtime_metrics_subscription_config { + realtime_metrics_subscription_status = %q + } + } +} +`, status)) +} From 4ef8063987c27badad5d9d42d9f93b5f88d9099a Mon Sep 17 00:00:00 2001 From: shuheiktgw Date: Mon, 15 Mar 2021 08:35:16 +0900 Subject: [PATCH 3/6] Add a document for aws_cloudfront_monitoring_subscription resource --- ...ront_monitoring_subscription.html.markdown | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 website/docs/r/cloudfront_monitoring_subscription.html.markdown diff --git a/website/docs/r/cloudfront_monitoring_subscription.html.markdown b/website/docs/r/cloudfront_monitoring_subscription.html.markdown new file mode 100644 index 00000000000..63676258745 --- /dev/null +++ b/website/docs/r/cloudfront_monitoring_subscription.html.markdown @@ -0,0 +1,54 @@ +--- +subcategory: "CloudFront" +layout: "aws" +page_title: "AWS: aws_cloudfront_monitoring_subscription" +description: |- + Provides a CloudFront monitoring subscription resource. +--- + +# Resource: aws_cloudfront_monitoring_subscription + +Provides a CloudFront real-time log configuration resource. + +## Example Usage + +```hcl +resource "aws_cloudfront_monitoring_subscription" "example" { + distribution_id = aws_cloudfront_distribution.example.id + + monitoring_subscription { + realtime_metrics_subscription_config { + realtime_metrics_subscription_status = "Enabled" + } + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `distribution_id` - (Required) The ID of the distribution that you are enabling metrics for. +* `monitoring_subscription` - (Required) A monitoring subscription. This structure contains information about whether additional CloudWatch metrics are enabled for a given CloudFront distribution. + +The `monitoring_subscription` object supports the following argument: + +* `realtime_metrics_subscription_config` - (Required) A subscription configuration for additional CloudWatch metrics. + +The `realtime_metrics_subscription_config` object supports the following argument: + +* `realtime_metrics_subscription_status` - (Required) A flag that indicates whether additional CloudWatch metrics are enabled for a given CloudFront distribution. Valid values are `Enabled` and `Disabled`. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The ID of the CloudFront monitoring subscription, which corresponds to the `distribution_id`. + +## Import + +CloudFront monitoring subscription can be imported using the id, e.g. + +``` +$ terraform import aws_cloudfront_monitoring_subscription.example E3QYSUHO4VYRGB +``` From c38fe522539561b41a221ca781c0959aa0ee3db0 Mon Sep 17 00:00:00 2001 From: bill-rich Date: Wed, 30 Jun 2021 14:29:13 -0700 Subject: [PATCH 4/6] Add CHANGELOG entry --- .changelog/18083.txt | 3 ++ ..._aws_cloudfront_monitoring_subscription.go | 14 +++++---- ...cloudfront_monitoring_subscription_test.go | 30 +++++-------------- ...ront_monitoring_subscription.html.markdown | 8 ++--- 4 files changed, 22 insertions(+), 33 deletions(-) create mode 100644 .changelog/18083.txt diff --git a/.changelog/18083.txt b/.changelog/18083.txt new file mode 100644 index 00000000000..7aff48adf89 --- /dev/null +++ b/.changelog/18083.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_cloudfront_monitoring_subscription +``` diff --git a/aws/resource_aws_cloudfront_monitoring_subscription.go b/aws/resource_aws_cloudfront_monitoring_subscription.go index 71664e4c3a5..8cba547f596 100644 --- a/aws/resource_aws_cloudfront_monitoring_subscription.go +++ b/aws/resource_aws_cloudfront_monitoring_subscription.go @@ -16,9 +16,10 @@ func resourceAwsCloudFrontMonitoringSubscription() *schema.Resource { return &schema.Resource{ Create: resourceAwsCloudFrontMonitoringSubscriptionCreate, Read: resourceAwsCloudFrontMonitoringSubscriptionRead, + Update: resourceAwsCloudFrontMonitoringSubscriptionCreate, Delete: resourceAwsCloudFrontMonitoringSubscriptionDelete, Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, + State: resourceAwsCloudFrontMonitoringSubscriptionImport, }, Schema: map[string]*schema.Schema{ @@ -31,7 +32,6 @@ func resourceAwsCloudFrontMonitoringSubscription() *schema.Resource { "monitoring_subscription": { Type: schema.TypeList, Required: true, - ForceNew: true, MinItems: 1, MaxItems: 1, Elem: &schema.Resource{ @@ -39,7 +39,6 @@ func resourceAwsCloudFrontMonitoringSubscription() *schema.Resource { "realtime_metrics_subscription_config": { Type: schema.TypeList, Required: true, - ForceNew: true, MinItems: 1, MaxItems: 1, Elem: &schema.Resource{ @@ -47,7 +46,6 @@ func resourceAwsCloudFrontMonitoringSubscription() *schema.Resource { "realtime_metrics_subscription_status": { Type: schema.TypeString, Required: true, - ForceNew: true, ValidateFunc: validation.StringInSlice(cloudfront.RealtimeMetricsSubscriptionStatus_Values(), false), }, }, @@ -86,7 +84,7 @@ func resourceAwsCloudFrontMonitoringSubscriptionRead(d *schema.ResourceData, met subscription, err := finder.MonitoringSubscriptionByDistributionId(conn, d.Id()) - if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, cloudfront.ErrCodeNoSuchDistribution) { + if tfawserr.ErrCodeEquals(err, cloudfront.ErrCodeNoSuchDistribution) { log.Printf("[WARN] CloudFront Distribution (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -105,7 +103,6 @@ func resourceAwsCloudFrontMonitoringSubscriptionRead(d *schema.ResourceData, met return nil } - d.Set("distribution_id", d.Id()) if err := d.Set("monitoring_subscription", flattenCloudFrontMonitoringSubscription(subscription)); err != nil { return fmt.Errorf("error setting monitoring_subscription: %w", err) } @@ -163,3 +160,8 @@ func flattenCloudFrontMonitoringSubscription(subscription *cloudfront.Monitoring func flattenCloudFrontRealtimeMetricsSubscriptionConfig(config *cloudfront.RealtimeMetricsSubscriptionConfig) []interface{} { return []interface{}{map[string]interface{}{"realtime_metrics_subscription_status": config.RealtimeMetricsSubscriptionStatus}} } + +func resourceAwsCloudFrontMonitoringSubscriptionImport(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { + d.Set("distribution_id", d.Id()) + return []*schema.ResourceData{d}, nil +} diff --git a/aws/resource_aws_cloudfront_monitoring_subscription_test.go b/aws/resource_aws_cloudfront_monitoring_subscription_test.go index 4397e9b7c48..31dbb18e8c8 100644 --- a/aws/resource_aws_cloudfront_monitoring_subscription_test.go +++ b/aws/resource_aws_cloudfront_monitoring_subscription_test.go @@ -78,7 +78,7 @@ func TestAccAWSCloudFrontMonitoringSubscription_basic(t *testing.T) { CheckDestroy: testAccCheckCloudFrontMonitoringSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSCloudFrontMonitoringSubscriptionConfig(), + Config: testAccAWSCloudFrontMonitoringSubscriptionConfig("Enabled"), Check: resource.ComposeTestCheckFunc( testAccCheckCloudFrontMonitoringSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "distribution_id"), @@ -106,7 +106,7 @@ func TestAccAWSCloudFrontMonitoringSubscription_disappears(t *testing.T) { CheckDestroy: testAccCheckCloudFrontMonitoringSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSCloudFrontMonitoringSubscriptionConfig(), + Config: testAccAWSCloudFrontMonitoringSubscriptionConfig("Enabled"), Check: resource.ComposeTestCheckFunc( testAccCheckCloudFrontMonitoringSubscriptionExists(resourceName, &v), testAccCheckResourceDisappears(testAccProvider, resourceAwsCloudFrontMonitoringSubscription(), resourceName), @@ -117,7 +117,7 @@ func TestAccAWSCloudFrontMonitoringSubscription_disappears(t *testing.T) { }) } -func TestAccAWSCloudFrontMonitoringSubscription_RealtimeMetricsSubscriptionConfig(t *testing.T) { +func TestAccAWSCloudFrontMonitoringSubscription_update(t *testing.T) { var v cloudfront.MonitoringSubscription resourceName := "aws_cloudfront_monitoring_subscription.test" @@ -127,7 +127,7 @@ func TestAccAWSCloudFrontMonitoringSubscription_RealtimeMetricsSubscriptionConfi CheckDestroy: testAccCheckCloudFrontMonitoringSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSCloudFrontMonitoringSubscriptionRealtimeMetricsSubscriptionConfigConfig("Enabled"), + Config: testAccAWSCloudFrontMonitoringSubscriptionConfig("Enabled"), Check: resource.ComposeTestCheckFunc( testAccCheckCloudFrontMonitoringSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "distribution_id"), @@ -142,7 +142,7 @@ func TestAccAWSCloudFrontMonitoringSubscription_RealtimeMetricsSubscriptionConfi ImportStateVerify: true, }, { - Config: testAccAWSCloudFrontMonitoringSubscriptionRealtimeMetricsSubscriptionConfigConfig("Disabled"), + Config: testAccAWSCloudFrontMonitoringSubscriptionConfig("Disabled"), Check: resource.ComposeTestCheckFunc( testAccCheckCloudFrontMonitoringSubscriptionExists(resourceName, &v), resource.TestCheckResourceAttrSet(resourceName, "distribution_id"), @@ -249,23 +249,7 @@ resource "aws_cloudfront_distribution" "test" { ` } -func testAccAWSCloudFrontMonitoringSubscriptionConfig() string { - return composeConfig( - testAccAWSCloudFrontMonitoringSubscriptionConfigBase(), - ` -resource "aws_cloudfront_monitoring_subscription" "test" { - distribution_id = aws_cloudfront_distribution.test.id - - monitoring_subscription { - realtime_metrics_subscription_config { - realtime_metrics_subscription_status = "Enabled" - } - } -} -`) -} - -func testAccAWSCloudFrontMonitoringSubscriptionRealtimeMetricsSubscriptionConfigConfig(status string) string { +func testAccAWSCloudFrontMonitoringSubscriptionConfig(status string) string { return composeConfig( testAccAWSCloudFrontMonitoringSubscriptionConfigBase(), fmt.Sprintf(` @@ -274,7 +258,7 @@ resource "aws_cloudfront_monitoring_subscription" "test" { monitoring_subscription { realtime_metrics_subscription_config { - realtime_metrics_subscription_status = %q + realtime_metrics_subscription_status = %[1]q } } } diff --git a/website/docs/r/cloudfront_monitoring_subscription.html.markdown b/website/docs/r/cloudfront_monitoring_subscription.html.markdown index 63676258745..53655a9e6bc 100644 --- a/website/docs/r/cloudfront_monitoring_subscription.html.markdown +++ b/website/docs/r/cloudfront_monitoring_subscription.html.markdown @@ -31,13 +31,13 @@ The following arguments are supported: * `distribution_id` - (Required) The ID of the distribution that you are enabling metrics for. * `monitoring_subscription` - (Required) A monitoring subscription. This structure contains information about whether additional CloudWatch metrics are enabled for a given CloudFront distribution. -The `monitoring_subscription` object supports the following argument: +### monitoring_subscription -* `realtime_metrics_subscription_config` - (Required) A subscription configuration for additional CloudWatch metrics. +* `realtime_metrics_subscription_config` - (Required) A subscription configuration for additional CloudWatch metrics. See below. -The `realtime_metrics_subscription_config` object supports the following argument: +### realtime_metrics_subscription_config -* `realtime_metrics_subscription_status` - (Required) A flag that indicates whether additional CloudWatch metrics are enabled for a given CloudFront distribution. Valid values are `Enabled` and `Disabled`. +* `realtime_metrics_subscription_status` - (Required) A flag that indicates whether additional CloudWatch metrics are enabled for a given CloudFront distribution. Valid values are `Enabled` and `Disabled`. See below. ## Attributes Reference From b8d1828673262c3cc0e9733f022d8a38c8ece4ac Mon Sep 17 00:00:00 2001 From: bill-rich Date: Wed, 30 Jun 2021 14:50:24 -0700 Subject: [PATCH 5/6] Add ErrorCheck --- aws/resource_aws_cloudfront_monitoring_subscription_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/aws/resource_aws_cloudfront_monitoring_subscription_test.go b/aws/resource_aws_cloudfront_monitoring_subscription_test.go index 31dbb18e8c8..d5ebde409f9 100644 --- a/aws/resource_aws_cloudfront_monitoring_subscription_test.go +++ b/aws/resource_aws_cloudfront_monitoring_subscription_test.go @@ -76,6 +76,7 @@ func TestAccAWSCloudFrontMonitoringSubscription_basic(t *testing.T) { PreCheck: func() { testAccPreCheck(t); testAccPartitionHasServicePreCheck(cloudfront.EndpointsID, t) }, Providers: testAccProviders, CheckDestroy: testAccCheckCloudFrontMonitoringSubscriptionDestroy, + ErrorCheck: testAccErrorCheck(t, cloudfront.EndpointsID), Steps: []resource.TestStep{ { Config: testAccAWSCloudFrontMonitoringSubscriptionConfig("Enabled"), @@ -104,6 +105,7 @@ func TestAccAWSCloudFrontMonitoringSubscription_disappears(t *testing.T) { PreCheck: func() { testAccPreCheck(t); testAccPartitionHasServicePreCheck(cloudfront.EndpointsID, t) }, Providers: testAccProviders, CheckDestroy: testAccCheckCloudFrontMonitoringSubscriptionDestroy, + ErrorCheck: testAccErrorCheck(t, cloudfront.EndpointsID), Steps: []resource.TestStep{ { Config: testAccAWSCloudFrontMonitoringSubscriptionConfig("Enabled"), @@ -125,6 +127,7 @@ func TestAccAWSCloudFrontMonitoringSubscription_update(t *testing.T) { PreCheck: func() { testAccPreCheck(t); testAccPartitionHasServicePreCheck(cloudfront.EndpointsID, t) }, Providers: testAccProviders, CheckDestroy: testAccCheckCloudFrontMonitoringSubscriptionDestroy, + ErrorCheck: testAccErrorCheck(t, cloudfront.EndpointsID), Steps: []resource.TestStep{ { Config: testAccAWSCloudFrontMonitoringSubscriptionConfig("Enabled"), From 26a7810da31381b84f4031e6855fbec0d02feeb8 Mon Sep 17 00:00:00 2001 From: bill-rich Date: Wed, 30 Jun 2021 14:52:20 -0700 Subject: [PATCH 6/6] Fix example code language --- website/docs/r/cloudfront_monitoring_subscription.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/cloudfront_monitoring_subscription.html.markdown b/website/docs/r/cloudfront_monitoring_subscription.html.markdown index 53655a9e6bc..ce4de36850f 100644 --- a/website/docs/r/cloudfront_monitoring_subscription.html.markdown +++ b/website/docs/r/cloudfront_monitoring_subscription.html.markdown @@ -12,7 +12,7 @@ Provides a CloudFront real-time log configuration resource. ## Example Usage -```hcl +```terraform resource "aws_cloudfront_monitoring_subscription" "example" { distribution_id = aws_cloudfront_distribution.example.id