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

adds an event bus policy resource #16874

Merged
merged 20 commits into from Jun 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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 @@ -549,6 +549,7 @@ func Provider() *schema.Provider {
"aws_cloudfront_realtime_log_config": resourceAwsCloudFrontRealtimeLogConfig(),
"aws_cloudtrail": resourceAwsCloudTrail(),
"aws_cloudwatch_event_bus": resourceAwsCloudWatchEventBus(),
"aws_cloudwatch_event_bus_policy": resourceAwsCloudWatchEventBusPolicy(),
"aws_cloudwatch_event_permission": resourceAwsCloudWatchEventPermission(),
"aws_cloudwatch_event_rule": resourceAwsCloudWatchEventRule(),
"aws_cloudwatch_event_target": resourceAwsCloudWatchEventTarget(),
Expand Down
179 changes: 179 additions & 0 deletions aws/resource_aws_cloudwatch_event_bus_policy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
package aws

import (
"fmt"
"log"

"github.com/aws/aws-sdk-go/aws"
events "github.com/aws/aws-sdk-go/service/cloudwatchevents"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
tfevents "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/cloudwatchevents"
iamwaiter "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/iam/waiter"
)

func resourceAwsCloudWatchEventBusPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAwsCloudWatchEventBusPolicyCreate,
Read: resourceAwsCloudWatchEventBusPolicyRead,
Update: resourceAwsCloudWatchEventBusPolicyUpdate,
Delete: resourceAwsCloudWatchEventBusPolicyDelete,
Importer: &schema.ResourceImporter{
State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
d.Set("event_bus_name", d.Id())
return []*schema.ResourceData{d}, nil
},
},

Schema: map[string]*schema.Schema{
"event_bus_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validateCloudWatchEventBusNameOrARN,
Default: tfevents.DefaultEventBusName,
},
"policy": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringIsJSON,
DiffSuppressFunc: suppressEquivalentAwsPolicyDiffs,
},
},
}
}

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

eventBusName := d.Get("event_bus_name").(string)
policy := d.Get("policy").(string)

input := events.PutPermissionInput{
EventBusName: aws.String(eventBusName),
Policy: aws.String(policy),
}

log.Printf("[DEBUG] Creating CloudWatch Events policy: %s", input)
_, err := conn.PutPermission(&input)
if err != nil {
return fmt.Errorf("Creating CloudWatch Events policy failed: %w", err)
}

d.SetId(eventBusName)
Copy link
Collaborator

Choose a reason for hiding this comment

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

I might be wrong, but I'm on the fence about this not being a combination of eventBus + policy statement ID (unique), like in the event_permission resource.

I'd defer to core maintainers on this one

Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm on the fence of this not being a combination of bus name + statement Id - I suspect it's okay given you can have a single resource policy per bus, so I'll defer to core maintainers on that.

Copy link
Contributor

Choose a reason for hiding this comment

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

Considering the "aws_cloudwatch_event_bus_policy" resource supports multiple statements we think that making it unique for each event bus won't introduce limitations. Also this implementation appears to be consistent with the SDK/CLI, which don't model event bus permissions as independent resources.

Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't disagree. I don't just understand what the rationale was behind aws_cloudwatch_event_permission to create an unique ID back then: https://github.com/hashicorp/terraform-provider-aws/blob/fafcf78238182983aa8a5238c326f9049448aa70/aws/resource_aws_cloudwatch_event_permission.go#L103-L102

Copy link
Contributor

Choose a reason for hiding this comment

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

The "aws_cloudwatch_event_permission" resource only defines one statement in the policy, and it's therefore identified by it. The resource "aws_cloudwatch_event_policy" defines the complete policy for the event bus (possibly with multiple statements) and it's intended to be unique for each event bus.


return resourceAwsCloudWatchEventBusPolicyRead(d, meta)
}

// See also: https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/API_DescribeEventBus.html
func resourceAwsCloudWatchEventBusPolicyRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn

eventBusName := d.Id()

input := events.DescribeEventBusInput{
Name: aws.String(eventBusName),
}
var output *events.DescribeEventBusOutput
var err error
var policy *string

// Especially with concurrent PutPermission calls there can be a slight delay
err = resource.Retry(iamwaiter.PropagationTimeout, func() *resource.RetryError {
log.Printf("[DEBUG] Reading CloudWatch Events bus: %s", input)
output, err = conn.DescribeEventBus(&input)
if err != nil {
return resource.NonRetryableError(fmt.Errorf("reading CloudWatch Events permission (%s) failed: %w", d.Id(), err))
}

policy, err = getEventBusPolicy(output)
if err != nil {
return resource.RetryableError(err)
}
return nil
})

if isResourceTimeoutError(err) {
output, err = conn.DescribeEventBus(&input)
if output != nil {
policy, err = getEventBusPolicy(output)
}
}

if isResourceNotFoundError(err) {
log.Printf("[WARN] Policy on {%s} EventBus not found, removing from state", d.Id())
d.SetId("")
return nil
}
if err != nil {
return fmt.Errorf("error reading policy from CloudWatch EventBus (%s): %w", d.Id(), err)
}

busName := aws.StringValue(output.Name)
if busName == "" {
busName = tfevents.DefaultEventBusName
}
d.Set("event_bus_name", busName)

d.Set("policy", policy)

return nil
}

func getEventBusPolicy(output *events.DescribeEventBusOutput) (*string, error) {
if output == nil || output.Policy == nil {
return nil, &resource.NotFoundError{
Message: fmt.Sprintf("Policy for CloudWatch EventBus %s not found", *output.Name),
LastResponse: output,
}
}

return output.Policy, nil
}

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

Choose a reason for hiding this comment

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

Could you create a test updating a policy?

Copy link
Collaborator

Choose a reason for hiding this comment

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

testAccAWSCloudwatchEventBusPolicyConfigUpdate added.

conn := meta.(*AWSClient).cloudwatcheventsconn

eventBusName := d.Id()

input := events.PutPermissionInput{
EventBusName: aws.String(eventBusName),
Policy: aws.String(d.Get("policy").(string)),
}

log.Printf("[DEBUG] Update CloudWatch EventBus policy: %s", input)
_, err := conn.PutPermission(&input)
if isAWSErr(err, events.ErrCodeResourceNotFoundException, "") {
log.Printf("[WARN] CloudWatch EventBus %q not found, removing from state", d.Id())
d.SetId("")
return nil
}
if err != nil {
return fmt.Errorf("error updating policy for CloudWatch EventBus (%s): %w", d.Id(), err)
}

return resourceAwsCloudWatchEventBusPolicyRead(d, meta)
}

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

Choose a reason for hiding this comment

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

Could you create a test for this? e.g.

func TestAccAWSCloudWatchEventPermission_Disappears(t *testing.T) {

Copy link
Collaborator

Choose a reason for hiding this comment

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

Could you create a test for deletion?

Copy link
Collaborator

Choose a reason for hiding this comment

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

TestAccAWSCloudwatchEventBusPolicy_disappears added.

conn := meta.(*AWSClient).cloudwatcheventsconn

eventBusName := d.Id()
removeAllPermissions := true

input := events.RemovePermissionInput{
EventBusName: aws.String(eventBusName),
RemoveAllPermissions: &removeAllPermissions,
}

log.Printf("[DEBUG] Delete CloudWatch EventBus Policy: %s", input)
_, err := conn.RemovePermission(&input)
if isAWSErr(err, events.ErrCodeResourceNotFoundException, "") {
return nil
}
if err != nil {
return fmt.Errorf("error deleting policy for CloudWatch EventBus (%s): %w", d.Id(), err)
}
return nil
}
Loading