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

New resource: aws_securityhub_finding_aggregator #21560

Merged
Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 3 additions & 0 deletions .changelog/21560.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
aws_securityhub_finding_aggregator
```
1 change: 1 addition & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1519,6 +1519,7 @@ func Provider() *schema.Provider {
"aws_securityhub_product_subscription": securityhub.ResourceProductSubscription(),
"aws_securityhub_standards_control": securityhub.ResourceStandardsControl(),
"aws_securityhub_standards_subscription": securityhub.ResourceStandardsSubscription(),
"aws_securityhub_finding_aggregator": securityhub.ResourceFindingAggregator(),

"aws_serverlessapplicationrepository_cloudformation_stack": serverlessapprepo.ResourceCloudFormationStack(),

Expand Down
176 changes: 176 additions & 0 deletions internal/service/securityhub/finding_aggregator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
package securityhub

import (
"fmt"
"log"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/securityhub"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/flex"
)

const (
allRegions = "ALL_REGIONS"
allRegionsExceptSpecified = "ALL_REGIONS_EXCEPT_SPECIFIED"
specifiedRegions = "SPECIFIED_REGIONS"
)

func ResourceFindingAggregator() *schema.Resource {
return &schema.Resource{
Create: resourceFindingAggregatorCreate,
Read: resourceFindingAggregatorRead,
Update: resourceFindingAggregatorUpdate,
Delete: resourceFindingAggregatorDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},

Schema: map[string]*schema.Schema{
"linking_mode": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
allRegions,
allRegionsExceptSpecified,
specifiedRegions,
}, false),
},
"specified_regions": {
Type: schema.TypeSet,
MinItems: 1,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
}
}

func resourceFindingAggregatorCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).SecurityHubConn

linkingMode := d.Get("linking_mode").(string)

req := &securityhub.CreateFindingAggregatorInput{
RegionLinkingMode: &linkingMode,
}

if v, ok := d.GetOk("specified_regions"); ok && (linkingMode == allRegionsExceptSpecified || linkingMode == specifiedRegions) {
req.Regions = flex.ExpandStringSet(v.(*schema.Set))
}

log.Printf("[DEBUG] Creating Security Hub finding aggregator")

resp, err := conn.CreateFindingAggregator(req)

if err != nil {
return fmt.Errorf("Error creating finding aggregator for Security Hub: %s", err)
}

d.SetId(aws.StringValue(resp.FindingAggregatorArn))

return resourceFindingAggregatorRead(d, meta)
}

func resourceFindingAggregatorRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).SecurityHubConn

aggregatorArn := d.Id()

log.Printf("[DEBUG] Reading Security Hub finding aggregator to find %s", aggregatorArn)

aggregator, err := FindingAggregatorCheckExists(conn, aggregatorArn)

if err != nil {
return fmt.Errorf("Error reading Security Hub finding aggregator to find %s: %s", aggregatorArn, err)
}

if aggregator == nil {
log.Printf("[WARN] Security Hub finding aggregator (%s) not found, removing from state", aggregatorArn)
d.SetId("")
return nil
}

d.Set("linking_mode", aggregator.RegionLinkingMode)

if len(aggregator.Regions) > 0 {
d.Set("specified_regions", flex.FlattenStringList(aggregator.Regions))
}

return nil
}

func FindingAggregatorCheckExists(conn *securityhub.SecurityHub, findingAggregatorArn string) (*securityhub.GetFindingAggregatorOutput, error) {
input := &securityhub.ListFindingAggregatorsInput{}

var found *securityhub.GetFindingAggregatorOutput
var err error = nil

err = conn.ListFindingAggregatorsPages(input, func(page *securityhub.ListFindingAggregatorsOutput, lastPage bool) bool {
for _, aggregator := range page.FindingAggregators {
if aws.StringValue(aggregator.FindingAggregatorArn) == findingAggregatorArn {
getInput := &securityhub.GetFindingAggregatorInput{
FindingAggregatorArn: &findingAggregatorArn,
}
found, err = conn.GetFindingAggregator(getInput)
return false
}
}
return !lastPage
})

if err != nil {
return nil, err
}

return found, nil
}

func resourceFindingAggregatorUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).SecurityHubConn

aggregatorArn := d.Id()

linkingMode := d.Get("linking_mode").(string)

req := &securityhub.UpdateFindingAggregatorInput{
FindingAggregatorArn: &aggregatorArn,
RegionLinkingMode: &linkingMode,
}

if v, ok := d.GetOk("specified_regions"); ok && (linkingMode == allRegionsExceptSpecified || linkingMode == specifiedRegions) {
req.Regions = flex.ExpandStringSet(v.(*schema.Set))
}

resp, err := conn.UpdateFindingAggregator(req)

if err != nil {
return fmt.Errorf("Error updating Security Hub finding aggregator (%s): %w", aggregatorArn, err)
}

d.SetId(aws.StringValue(resp.FindingAggregatorArn))

return resourceFindingAggregatorRead(d, meta)
}

func resourceFindingAggregatorDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).SecurityHubConn

aggregatorArn := d.Id()

log.Printf("[DEBUG] Disabling Security Hub finding aggregator %s", aggregatorArn)

_, err := conn.DeleteFindingAggregator(&securityhub.DeleteFindingAggregatorInput{
FindingAggregatorArn: &aggregatorArn,
})

if err != nil {
return fmt.Errorf("Error disabling Security Hub finding aggregator %s: %s", aggregatorArn, err)
}

return nil
}
166 changes: 166 additions & 0 deletions internal/service/securityhub/finding_aggregator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
package securityhub_test

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/service/securityhub"
"github.com/hashicorp/aws-sdk-go-base/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/hashicorp/terraform-provider-aws/internal/acctest"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
tfsecurityhub "github.com/hashicorp/terraform-provider-aws/internal/service/securityhub"
)

func testAccFindingAggregator_basic(t *testing.T) {
resourceName := "aws_securityhub_finding_aggregator.test_aggregator"

resource.Test(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, securityhub.EndpointsID),
Providers: acctest.Providers,
CheckDestroy: testAccCheckFindingAggregatorDestroy,
Steps: []resource.TestStep{
{
Config: testAccFindingAggregatorAllRegionsConfig(),
Check: resource.ComposeTestCheckFunc(
testAccCheckFindingAggregatorExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "linking_mode", "ALL_REGIONS"),
resource.TestCheckNoResourceAttr(resourceName, "specified_regions"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccFindingAggregatorSpecifiedRegionsConfig(),
Check: resource.ComposeTestCheckFunc(
testAccCheckFindingAggregatorExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "linking_mode", "SPECIFIED_REGIONS"),
resource.TestCheckResourceAttr(resourceName, "specified_regions.#", "3"),
),
},
{
Config: testAccFindingAggregatorAllRegionsExceptSpecifiedConfig(),
Check: resource.ComposeTestCheckFunc(
testAccCheckFindingAggregatorExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "linking_mode", "ALL_REGIONS_EXCEPT_SPECIFIED"),
resource.TestCheckResourceAttr(resourceName, "specified_regions.#", "2"),
),
},
},
})
}

func testAccFindingAggregator_disappears(t *testing.T) {
resourceName := "aws_securityhub_finding_aggregator.test_aggregator"

resource.Test(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, securityhub.EndpointsID),
Providers: acctest.Providers,
CheckDestroy: testAccCheckFindingAggregatorDestroy,
Steps: []resource.TestStep{
{
Config: testAccFindingAggregatorAllRegionsConfig(),
Check: resource.ComposeTestCheckFunc(
testAccCheckFindingAggregatorExists(resourceName),
acctest.CheckResourceDisappears(acctest.Provider, tfsecurityhub.ResourceFindingAggregator(), resourceName),
),
ExpectNonEmptyPlan: true,
},
},
})
}

func testAccCheckFindingAggregatorExists(n string) 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 Security Hub finding aggregator ID is set")
}

conn := acctest.Provider.Meta().(*conns.AWSClient).SecurityHubConn

_, err := conn.GetFindingAggregator(&securityhub.GetFindingAggregatorInput{
FindingAggregatorArn: &rs.Primary.ID,
})

if err != nil {
return fmt.Errorf("Failed to get finding aggregator: %s", err)
}

return nil
}
}

func testAccCheckFindingAggregatorDestroy(s *terraform.State) error {
conn := acctest.Provider.Meta().(*conns.AWSClient).SecurityHubConn

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

_, err := conn.GetFindingAggregator(&securityhub.GetFindingAggregatorInput{
FindingAggregatorArn: &rs.Primary.ID,
})

if tfawserr.ErrMessageContains(err, securityhub.ErrCodeInvalidAccessException, "not subscribed to AWS Security Hub") {
continue
}

if err != nil {
return err
}

return fmt.Errorf("Security Hub Finding Aggregator %s still exists", rs.Primary.ID)
}

return nil
}

func testAccFindingAggregatorAllRegionsConfig() string {
return `
resource "aws_securityhub_account" "example" {}

resource "aws_securityhub_finding_aggregator" "test_aggregator" {
linking_mode = "ALL_REGIONS"

depends_on = [aws_securityhub_account.example]
}
`
}

func testAccFindingAggregatorSpecifiedRegionsConfig() string {
return `
resource "aws_securityhub_account" "example" {}

resource "aws_securityhub_finding_aggregator" "test_aggregator" {
linking_mode = "SPECIFIED_REGIONS"
specified_regions = ["eu-west-2", "eu-west-1", "us-east-1"]

depends_on = [aws_securityhub_account.example]
}
`
}

func testAccFindingAggregatorAllRegionsExceptSpecifiedConfig() string {
return `
resource "aws_securityhub_account" "example" {}

resource "aws_securityhub_finding_aggregator" "test_aggregator" {
linking_mode = "ALL_REGIONS_EXCEPT_SPECIFIED"
specified_regions = ["eu-west-2", "eu-west-1"]

depends_on = [aws_securityhub_account.example]
}
`
}
4 changes: 4 additions & 0 deletions internal/service/securityhub/securityhub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ func TestAccSecurityHub_serial(t *testing.T) {
"basic": testAccStandardsSubscription_basic,
"disappears": testAccStandardsSubscription_disappears,
},
"FindingAggregator": {
"basic": testAccFindingAggregator_basic,
"disappears": testAccFindingAggregator_disappears,
},
}

for group, m := range testCases {
Expand Down
Loading