Skip to content

Commit

Permalink
inspector2/enabler: Change account_ids to required
Browse files Browse the repository at this point in the history
  • Loading branch information
YakDriver committed Oct 27, 2022
1 parent 9337502 commit 67c65fc
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 61 deletions.
50 changes: 5 additions & 45 deletions internal/service/inspector2/enabler.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ func ResourceEnabler() *schema.Resource {
Schema: map[string]*schema.Schema{
"account_ids": {
Type: schema.TypeSet,
Optional: true,
MinItems: 1,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: verify.ValidAccountID,
Expand All @@ -66,26 +67,16 @@ const (

func resourceEnablerCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).Inspector2Conn
fmt.Printf("create\n")

in := &inspector2.EnableInput{
AccountIds: flex.ExpandStringValueSet(d.Get("account_ids").(*schema.Set)),
ResourceTypes: expandResourceScanTypes(flex.ExpandStringValueSet(d.Get("resource_types").(*schema.Set))),
ClientToken: aws.String(resource.UniqueId()),
}

if v, ok := d.GetOk("account_ids"); ok && v.(*schema.Set).Len() > 0 {
in.AccountIds = flex.ExpandStringValueSet(d.Get("account_ids").(*schema.Set))
}

fmt.Printf("create in: %+v\n", in)

id := EnablerID(in.AccountIds, flex.ExpandStringValueSet(d.Get("resource_types").(*schema.Set)))

fmt.Printf("enabler id: %+v\n", id)

out, err := conn.Enable(ctx, in)
fmt.Printf("Enable: %+v, err: %s\n", out, err)

if err != nil {
return create.DiagError(names.Inspector2, create.ErrActionCreating, ResNameEnabler, id, err)
}
Expand All @@ -96,8 +87,6 @@ func resourceEnablerCreate(ctx context.Context, d *schema.ResourceData, meta int

d.SetId(id)

fmt.Printf("enable called, now waiting enable\n")

if err := waitEnabled(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil {
return create.DiagError(names.Inspector2, create.ErrActionWaitingForCreation, ResNameEnabler, d.Id(), err)
}
Expand All @@ -107,7 +96,6 @@ func resourceEnablerCreate(ctx context.Context, d *schema.ResourceData, meta int

func resourceEnablerRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).Inspector2Conn
fmt.Printf("reading\n")

s, err := FindAccountStatuses(ctx, conn, d.Id())
if err != nil {
Expand All @@ -128,13 +116,6 @@ func resourceEnablerRead(ctx context.Context, d *schema.ResourceData, meta inter
}
}

// special case: if no acct id set, aws will return current account - this should not be a diff
if v, ok := d.GetOk("account_ids"); !ok || v.(*schema.Set).Len() == 0 {
if len(enabledAccounts) == 1 && aws.ToString(enabledAccounts[0]) == meta.(*conns.AWSClient).AccountID {
return nil
}
}

if err := d.Set("account_ids", flex.FlattenStringSet(enabledAccounts)); err != nil {
return create.DiagError(names.Inspector2, create.ErrActionReading, ResNameEnabler, d.Id(), err)
}
Expand All @@ -144,25 +125,17 @@ func resourceEnablerRead(ctx context.Context, d *schema.ResourceData, meta inter

func resourceEnablerDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).Inspector2Conn
fmt.Printf("delete %d\n", 1)

in := &inspector2.DisableInput{
AccountIds: flex.ExpandStringValueSet(d.Get("account_ids").(*schema.Set)),
ResourceTypes: expandResourceScanTypes(flex.ExpandStringValueSet(d.Get("resource_types").(*schema.Set))),
}

if v, ok := d.GetOk("account_ids"); ok && v.(*schema.Set).Len() > 0 {
in.AccountIds = flex.ExpandStringValueSet(d.Get("account_ids").(*schema.Set))
}

fmt.Printf("delete %d\n", 2)

_, err := conn.Disable(ctx, in)
if err != nil {
return create.DiagError(names.Inspector2, create.ErrActionDeleting, ResNameEnabler, d.Id(), err)
}

fmt.Printf("delete %d\n", 3)

if err := waitDisabled(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil {
return create.DiagError(names.Inspector2, create.ErrActionWaitingForDeletion, ResNameEnabler, d.Id(), err)
}
Expand All @@ -176,7 +149,6 @@ const (
)

func waitEnabled(ctx context.Context, conn *inspector2.Client, id string, timeout time.Duration) error {
fmt.Printf("waitEnabled\n")
stateConf := &resource.StateChangeConf{
Pending: []string{string(types.StatusEnabling), StatusDisabledEnabled, StatusInProgress, string(types.StatusDisabled)},
Target: []string{string(types.StatusEnabled)},
Expand All @@ -192,8 +164,6 @@ func waitEnabled(ctx context.Context, conn *inspector2.Client, id string, timeou
}

func waitDisabled(ctx context.Context, conn *inspector2.Client, id string, timeout time.Duration) error {
fmt.Printf("delete %d\n", 4)

stateConf := &resource.StateChangeConf{
Pending: []string{string(types.StatusDisabling), StatusDisabledEnabled, StatusInProgress, string(types.StatusEnabled)},
Target: []string{string(types.StatusDisabled)},
Expand All @@ -208,7 +178,6 @@ func waitDisabled(ctx context.Context, conn *inspector2.Client, id string, timeo

func statusEnable(ctx context.Context, conn *inspector2.Client, id string, timeout time.Duration) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
fmt.Printf("statusEnable\n")
st, err := FindAccountStatuses(ctx, conn, id)

if errs.Contains(err, string(types.ErrorCodeAlreadyEnabled)) {
Expand All @@ -233,8 +202,6 @@ func statusEnable(ctx context.Context, conn *inspector2.Client, id string, timeo
return nil, "", err
}

fmt.Printf("st: %+v\n", st)

hasEnabled := false
hasDisabled := false

Expand Down Expand Up @@ -390,22 +357,15 @@ func expandResourceScanTypes(s []string) []types.ResourceScanType {
}

func EnablerID(accountIDs []string, types []string) string {
if len(accountIDs) == 0 {
return strings.Join(types, ":")
}
return fmt.Sprintf("%s-%s", strings.Join(accountIDs, ":"), strings.Join(types, ":"))
}

func parseEnablerID(id string) ([]string, []string, error) {
parts := strings.Split(id, "-")

if len(parts) < 1 || len(parts) > 2 {
if len(parts) != 2 {
return nil, nil, fmt.Errorf("unexpected ID format (%s), expected <account-ids (':' separated)>-<types (':' separated)>", id)
}

if len(parts) == 1 {
return nil, strings.Split(parts[0], ":"), nil
}

return strings.Split(parts[0], ":"), strings.Split(parts[1], ":"), nil
}
22 changes: 8 additions & 14 deletions internal/service/inspector2/enabler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ func testAccEnabler_basic(t *testing.T) {
{
Config: testAccEnablerConfig_basic([]string{"ECR"}),
Check: resource.ComposeTestCheckFunc(
testAccCheckEnablerExists(tfinspector2.EnablerID(nil, []string{"ECR"})),
resource.TestCheckResourceAttr(resourceName, "account_ids.#", "0"),
testAccCheckEnablerExists([]string{"ECR"}),
resource.TestCheckResourceAttr(resourceName, "account_ids.#", "1"),
resource.TestCheckResourceAttrPair(resourceName, "account_ids.0", "data.aws_caller_identity.current", "account_id"),
resource.TestCheckResourceAttr(resourceName, "resource_types.#", "1"),
resource.TestCheckResourceAttr(resourceName, "resource_types.0", "ECR"),
),
Expand All @@ -74,9 +75,9 @@ func testAccEnabler_accountID(t *testing.T) {
CheckDestroy: testAccCheckEnablerDestroy,
Steps: []resource.TestStep{
{
Config: testAccEnablerConfig_accountID([]string{"EC2", "ECR"}),
Config: testAccEnablerConfig_basic([]string{"EC2", "ECR"}),
Check: resource.ComposeTestCheckFunc(
testAccCheckEnablerExists(tfinspector2.EnablerID(nil, []string{"EC2", "ECR"})),
testAccCheckEnablerExists([]string{"EC2", "ECR"}),
resource.TestCheckResourceAttr(resourceName, "account_ids.#", "1"),
resource.TestCheckResourceAttrPair(resourceName, "account_ids.0", "data.aws_caller_identity.current", "account_id"),
resource.TestCheckResourceAttr(resourceName, "resource_types.#", "2"),
Expand Down Expand Up @@ -105,7 +106,7 @@ func testAccEnabler_disappears(t *testing.T) {
{
Config: testAccEnablerConfig_basic([]string{"ECR"}),
Check: resource.ComposeTestCheckFunc(
testAccCheckEnablerExists(tfinspector2.EnablerID(nil, []string{"ECR"})),
testAccCheckEnablerExists([]string{"ECR"}),
acctest.CheckResourceDisappears(acctest.Provider, tfinspector2.ResourceEnabler(), resourceName),
),
ExpectNonEmptyPlan: true,
Expand Down Expand Up @@ -145,10 +146,11 @@ func testAccCheckEnablerDestroy(s *terraform.State) error {
return nil
}

func testAccCheckEnablerExists(id string) resource.TestCheckFunc {
func testAccCheckEnablerExists(t []string) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := acctest.Provider.Meta().(*conns.AWSClient).Inspector2Conn

id := tfinspector2.EnablerID([]string{acctest.Provider.Meta().(*conns.AWSClient).AccountID}, t)
st, err := tfinspector2.FindAccountStatuses(context.Background(), conn, id)
if err != nil {
return create.Error(names.Inspector2, create.ErrActionCheckingExistence, tfinspector2.ResNameEnabler, id, err)
Expand All @@ -165,14 +167,6 @@ func testAccCheckEnablerExists(id string) resource.TestCheckFunc {

func testAccEnablerConfig_basic(types []string) string {
return fmt.Sprintf(`
resource "aws_inspector2_enabler" "test" {
resource_types = [%[1]q]
}
`, strings.Join(types, `", "`))
}

func testAccEnablerConfig_accountID(types []string) string {
return fmt.Sprintf(`
data "aws_caller_identity" "current" {}
resource "aws_inspector2_enabler" "test" {
Expand Down
16 changes: 14 additions & 2 deletions website/docs/r/inspector2_enabler.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,27 @@ resource "aws_inspector2_enabler" "example" {
}
```

### For the Calling Account

```terraform
data "aws_caller_identity" "current" {}
resource "aws_inspector2_enabler" "test" {
account_ids = [data.aws_caller_identity.current.account_id]
resource_types = ["ECR", "EC2"]
}
```

## Argument Reference

The following arguments are required:

* `account_ids` - (Required) Set of account IDs.
* `resource_types` - (Required) Type of resources to scan. Valid values are `EC2` and `ECR`. If you only use one type, Terraform will ignore the status of the other type.

The following arguments are optional:
## Attributes Reference

* `account_ids` - (Optional) Set of account IDs. The default is to enable scans on the account where the resource is used.
There are no attributes for this resource.

## Timeouts

Expand Down

0 comments on commit 67c65fc

Please sign in to comment.