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

Add resource aws_cloudwatch_event_bus #10256

Merged
merged 1 commit into from
Oct 16, 2020
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 aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,7 @@ func Provider() terraform.ResourceProvider {
"aws_cloudfront_origin_access_identity": resourceAwsCloudFrontOriginAccessIdentity(),
"aws_cloudfront_public_key": resourceAwsCloudFrontPublicKey(),
"aws_cloudtrail": resourceAwsCloudTrail(),
"aws_cloudwatch_event_bus": resourceAwsCloudWatchEventBus(),
"aws_cloudwatch_event_permission": resourceAwsCloudWatchEventPermission(),
"aws_cloudwatch_event_rule": resourceAwsCloudWatchEventRule(),
"aws_cloudwatch_event_target": resourceAwsCloudWatchEventTarget(),
Expand Down
100 changes: 100 additions & 0 deletions aws/resource_aws_cloudwatch_event_bus.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package aws

import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"log"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)

func resourceAwsCloudWatchEventBus() *schema.Resource {
return &schema.Resource{
Create: resourceAwsCloudWatchEventBusCreate,
Read: resourceAwsCloudWatchEventBusRead,
Delete: resourceAwsCloudWatchEventBusDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateCloudWatchEventBusName,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func resourceAwsCloudWatchEventBusCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn

eventBusName := d.Get("name").(string)
params := &cloudwatchevents.CreateEventBusInput{
Name: aws.String(eventBusName),
}

log.Printf("[DEBUG] Creating CloudWatch Event Bus: %v", params)

_, err := conn.CreateEventBus(params)
if err != nil {
return fmt.Errorf("Creating CloudWatch Event Bus %v failed: %v", eventBusName, err)
}

d.SetId(eventBusName)

log.Printf("[INFO] CloudWatch Event Bus %v created", d.Id())

return resourceAwsCloudWatchEventBusRead(d, meta)
}

func resourceAwsCloudWatchEventBusRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
log.Printf("[DEBUG] Reading CloudWatch Event Bus: %v", d.Id())

input := &cloudwatchevents.DescribeEventBusInput{
Name: aws.String(d.Id()),
}

output, err := conn.DescribeEventBus(input)
if isAWSErr(err, cloudwatchevents.ErrCodeResourceNotFoundException, "") {
log.Printf("[WARN] CloudWatch Event Bus (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
if err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

We need to handle the case where the resource has been deleted outside Terraform by checking for a NotFound error, maybe:

if isAWSErr(err, events.ErrCodeResourceNotFoundException, "") {
	log.Printf("[WARN] CloudWatch Event Bus (%s) not found, removing from state", d.Id())
	d.SetId("")
	return nil
}

other errors can be wrapped:

if err != nil {
	return fmt.Errorf("error reading CloudWatch Event Bus: %s", err)
}

This can be tested by adding a _disappears test case, for example:
https://github.com/terraform-providers/terraform-provider-aws/blob/4875ae5fef0990f4a7e3768c81fcc732b90e0f13/aws/resource_aws_cloudwatch_log_stream_test.go#L33-L52

return fmt.Errorf("error reading CloudWatch Event Bus: %s", err)
}

log.Printf("[DEBUG] Found CloudWatch Event bus: %#v", *output)

d.Set("arn", output.Arn)
d.Set("name", output.Name)

return nil
}

func resourceAwsCloudWatchEventBusDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
log.Printf("[INFO] Deleting CloudWatch Event Bus: %v", d.Id())
_, err := conn.DeleteEventBus(&cloudwatchevents.DeleteEventBusInput{
Name: aws.String(d.Id()),
})
if isAWSErr(err, cloudwatchevents.ErrCodeResourceNotFoundException, "") {
log.Printf("[WARN] CloudWatch Event Bus (%s) not found", d.Id())
return nil
}
if err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

Please add the "resource not found" checking you now have in resourceAwsCloudWatchEventBusRead() here also.
Thanks.

return fmt.Errorf("Error deleting CloudWatch Event Bus %v: %v", d.Id(), err)
}
log.Printf("[INFO] CloudWatch Event Bus %v deleted", d.Id())

return nil
}
186 changes: 186 additions & 0 deletions aws/resource_aws_cloudwatch_event_bus_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
package aws

import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
"log"
"testing"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func init() {
resource.AddTestSweepers("aws_cloudwatch_event_bus", &resource.Sweeper{
Name: "aws_cloudwatch_event_bus",
F: testSweepCloudWatchEventBuses,
Copy link
Contributor

@ewbankkit ewbankkit Feb 21, 2020

Choose a reason for hiding this comment

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

It looks like an event bus can't be deleted if it has associated rules or targets so we'll need to add

Dependencies: []string{...},

here.

Dependencies: []string{
"aws_cloudwatch_event_rule",
"aws_cloudwatch_event_target",
},
})
}

func testSweepCloudWatchEventBuses(region string) error {
client, err := sharedClientForRegion(region)
if err != nil {
return fmt.Errorf("Error getting client: %s", err)
}
conn := client.(*AWSClient).cloudwatcheventsconn

input := &cloudwatchevents.ListEventBusesInput{}

for {
output, err := conn.ListEventBuses(input)
if err != nil {
if testSweepSkipSweepError(err) {
log.Printf("[WARN] Skipping CloudWatch Event Bus sweep for %s: %s", region, err)
return nil
}
return fmt.Errorf("Error retrieving CloudWatch Event Buses: %s", err)
}

if len(output.EventBuses) == 0 {
log.Print("[DEBUG] No CloudWatch Event Buses to sweep")
return nil
}

for _, eventBus := range output.EventBuses {
name := aws.StringValue(eventBus.Name)
if name == "default" {
continue
}

log.Printf("[INFO] Deleting CloudWatch Event Bus %s", name)
_, err := conn.DeleteEventBus(&cloudwatchevents.DeleteEventBusInput{
Name: aws.String(name),
})
if err != nil {
return fmt.Errorf("Error deleting CloudWatch Event Bus %s: %s", name, err)
}
}

if output.NextToken == nil {
break
}
input.NextToken = output.NextToken
}

return nil
}

func TestAccAWSCloudWatchEventBus_basic(t *testing.T) {
var eventBusOutput cloudwatchevents.DescribeEventBusOutput
busName := acctest.RandomWithPrefix("tf-acc-test")
busNameModified := acctest.RandomWithPrefix("tf-acc-test")
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSCloudWatchEventBusDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSCloudWatchEventBusConfig(busName),
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudWatchEventBusExists("aws_cloudwatch_event_bus.foo", &eventBusOutput),
resource.TestCheckResourceAttr("aws_cloudwatch_event_bus.foo", "name", busName),
),
},
{
Config: testAccAWSCloudWatchEventBusConfig(busNameModified),
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudWatchEventBusExists("aws_cloudwatch_event_bus.foo", &eventBusOutput),
resource.TestCheckResourceAttr("aws_cloudwatch_event_bus.foo", "name", busNameModified),
),
},
},
})
}

func TestAccAWSCloudWatchEventBus_disappears(t *testing.T) {
var eventBusOutput cloudwatchevents.DescribeEventBusOutput
busName := acctest.RandomWithPrefix("tf-acc-test")
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSCloudWatchEventBusDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSCloudWatchEventBusConfig(busName),
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudWatchEventBusExists("aws_cloudwatch_event_bus.foo", &eventBusOutput),
testAccCheckCloudWatchEventBusDisappears(&eventBusOutput),
),
ExpectNonEmptyPlan: true,
},
},
})
}

func testAccCheckAWSCloudWatchEventBusDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).cloudwatcheventsconn

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

params := cloudwatchevents.DescribeEventBusInput{
Name: aws.String(rs.Primary.ID),
}

resp, err := conn.DescribeEventBus(&params)

if err == nil {
return fmt.Errorf("CloudWatch Event Bus %q still exists: %s",
rs.Primary.ID, resp)
}
}

return nil
}

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

conn := testAccProvider.Meta().(*AWSClient).cloudwatcheventsconn
params := cloudwatchevents.DescribeEventBusInput{
Name: aws.String(rs.Primary.ID),
}
resp, err := conn.DescribeEventBus(&params)
if err != nil {
return err
}
if resp == nil {
return fmt.Errorf("Event Bus not found")
}

*v = *resp

return nil
}
}

func testAccCheckCloudWatchEventBusDisappears(v *cloudwatchevents.DescribeEventBusOutput) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).cloudwatcheventsconn
opts := &cloudwatchevents.DeleteEventBusInput{
Name: v.Name,
}
_, err := conn.DeleteEventBus(opts)
return err
}
}

func testAccAWSCloudWatchEventBusConfig(name string) string {
return fmt.Sprintf(`
resource "aws_cloudwatch_event_bus" "foo" {
name = "%s"
}
`, name)
}
6 changes: 6 additions & 0 deletions aws/validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -2407,3 +2407,9 @@ func validateRoute53ResolverName(v interface{}, k string) (ws []string, errors [

return
}

var validateCloudWatchEventBusName = validation.All(
validation.StringLenBetween(1, 256),
validation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9._\-]+$`), ""),
validation.StringDoesNotMatch(regexp.MustCompile(`^default$`), ""),
)
39 changes: 39 additions & 0 deletions aws/validators_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2985,3 +2985,42 @@ func TestValidateRoute53ResolverName(t *testing.T) {
}
}
}

func TestCloudWatchEventBusName(t *testing.T) {
cases := []struct {
Value string
IsValid bool
}{
{
Value: "",
IsValid: false,
},
{
Value: acctest.RandStringFromCharSet(256, acctest.CharSetAlpha),
IsValid: true,
},
{
Value: acctest.RandStringFromCharSet(257, acctest.CharSetAlpha),
IsValid: false,
},
{
Value: "aws.partner/test/test",
IsValid: false,
},
{
Value: "/test0._1-",
IsValid: false,
},
{
Value: "test0._1-",
IsValid: true,
},
}
for _, tc := range cases {
_, errors := validateCloudWatchEventBusName(tc.Value, "aws_cloudwatch_event_bus")
isValid := len(errors) == 0
if tc.IsValid != isValid {
t.Fatalf("Expected the AWS CloudWatch Event Bus Name to not trigger a validation error for %q", tc.Value)
}
}
}
3 changes: 3 additions & 0 deletions website/aws.erb
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,9 @@
<li>
<a href="/docs/providers/aws/r/cloudwatch_dashboard.html">aws_cloudwatch_dashboard</a>
</li>
<li>
<a href="/docs/providers/aws/r/cloudwatch_event_bus.html">aws_cloudwatch_event_bus</a>
</li>
<li>
<a href="/docs/providers/aws/r/cloudwatch_event_permission.html">aws_cloudwatch_event_permission</a>
</li>
Expand Down
Loading