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 data source: aws_ec2_managed_prefix_list #16738

Merged
merged 2 commits into from
Dec 17, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
153 changes: 153 additions & 0 deletions aws/data_source_aws_ec2_managed_prefix_list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package aws

import (
"context"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"

"github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags"
Copy link
Contributor

Choose a reason for hiding this comment

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

This should fix the importlint error:

Suggested change
"github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags"
"github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags"

)

func dataSourceAwsEc2ManagedPrefixList() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceAwsEc2ManagedPrefixListRead,
Copy link
Contributor

Choose a reason for hiding this comment

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

We're not quite ready to switch to the Context versions of the functions everywhere due to some known issues, but this is probably okay.

Schema: map[string]*schema.Schema{
"id": {
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: It would be easier to scan these attributes if they were sorted alphabetically and we may eventually enable tfproviderlint XS002

Type: schema.TypeString,
Computed: true,
Optional: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"entries": {
Type: schema.TypeSet,
Computed: true,
Elem: dataSourceAwsEc2ManagedPrefixListEntrySchema(),
},
"filter": dataSourceFiltersSchema(),
"owner_id": {
Type: schema.TypeString,
Computed: true,
},
"address_family": {
Type: schema.TypeString,
Computed: true,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"max_entries": {
Type: schema.TypeInt,
Computed: true,
},
"tags": tagsSchemaComputed(),
"version": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}

func dataSourceAwsEc2ManagedPrefixListEntrySchema() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func dataSourceAwsEc2ManagedPrefixListRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*AWSClient).ec2conn
ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig
filters, filtersOk := d.GetOk("filter")

input := ec2.DescribeManagedPrefixListsInput{}

if filtersOk {
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: Simplification:

Suggested change
filters, filtersOk := d.GetOk("filter")
input := ec2.DescribeManagedPrefixListsInput{}
if filtersOk {
input := ec2.DescribeManagedPrefixListsInput{}
if filters, ok := d.GetOk("filter"); ok {

input.Filters = buildAwsDataSourceFilters(filters.(*schema.Set))
}

if prefixListId, ok := d.GetOk("id"); ok {
input.PrefixListIds = aws.StringSlice([]string{prefixListId.(string)})
}

if prefixListName := d.Get("name"); prefixListName.(string) != "" {
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: Simplification:

Suggested change
if prefixListName := d.Get("name"); prefixListName.(string) != "" {
if prefixListName, ok := d.GetOk("name"); ok {

input.Filters = append(input.Filters, &ec2.Filter{
Name: aws.String("prefix-list-name"),
Values: aws.StringSlice([]string{prefixListName.(string)}),
})
}

out, err := conn.DescribeManagedPrefixListsWithContext(ctx, &input)

if err != nil {
return diag.FromErr(err)
Copy link
Contributor

Choose a reason for hiding this comment

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

Errors should return context for operators and code maintainers. Eventually this should get caught by: #15892

Suggested change
return diag.FromErr(err)
return diag.Errorf("error describing EC2 Managed Prefix Lists: %s", err)

}

if len(out.PrefixLists) < 1 {
return diag.Errorf("no managed prefix lists matched the given criteria")
}

if len(out.PrefixLists) > 1 {
return diag.Errorf("more than 1 prefix list matched the given criteria")
}

pl := *out.PrefixLists[0]

d.SetId(aws.StringValue(pl.PrefixListId))
d.Set("name", pl.PrefixListName)
d.Set("owner_id", pl.OwnerId)
d.Set("address_family", pl.AddressFamily)
d.Set("arn", pl.PrefixListArn)
d.Set("max_entries", pl.MaxEntries)
d.Set("version", pl.Version)

if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(pl.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil {
return diag.FromErr(err)
}

entries := &schema.Set{
F: schema.HashResource(dataSourceAwsEc2ManagedPrefixListEntrySchema()),
}
Copy link
Contributor

Choose a reason for hiding this comment

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

We can bypass schema.Set usage on flattening and just use []interface{} with append() 👍


err = conn.GetManagedPrefixListEntriesPages(
&ec2.GetManagedPrefixListEntriesInput{
PrefixListId: pl.PrefixListId,
},
func(output *ec2.GetManagedPrefixListEntriesOutput, last bool) bool {
for _, entry := range output.Entries {
entries.Add(map[string]interface{}{
"cidr": aws.StringValue(entry.Cidr),
"description": aws.StringValue(entry.Description),
})
}

return true
},
)

if err != nil {
return diag.FromErr(err)
Copy link
Contributor

Choose a reason for hiding this comment

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

Error context:

Suggested change
return diag.FromErr(err)
return diag.Errorf("error getting EC2 Managed Prefix List (%s) Entries: %s", d.Id(), err)

}

if err := d.Set("entries", entries); err != nil {
return diag.FromErr(err)
}

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

import (
"fmt"
"regexp"
"testing"

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

func testAccDataSourceAwsEc2ManagedPrefixListGetIdByName(name string, id *string, arn *string) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).ec2conn

output, err := conn.DescribeManagedPrefixLists(&ec2.DescribeManagedPrefixListsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("prefix-list-name"),
Values: aws.StringSlice([]string{name}),
},
},
})

if err != nil {
return err
}

*id = *output.PrefixLists[0].PrefixListId
*arn = *output.PrefixLists[0].PrefixListArn
return nil
}
}

func TestAccDataSourceAwsEc2ManagedPrefixList_basic(t *testing.T) {
prefixListName := fmt.Sprintf("com.amazonaws.%s.s3", testAccGetRegion())
prefixListId := ""
prefixListArn := ""

resourceByName := "data.aws_ec2_managed_prefix_list.s3_by_name"
resourceById := "data.aws_ec2_managed_prefix_list.s3_by_id"
prefixListResourceName := "data.aws_prefix_list.s3_by_id"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceAwsEc2ManagedPrefixListConfig_basic,
Check: resource.ComposeTestCheckFunc(
testAccDataSourceAwsEc2ManagedPrefixListGetIdByName(prefixListName, &prefixListId, &prefixListArn),

resource.TestCheckResourceAttrPtr(resourceByName, "id", &prefixListId),
resource.TestCheckResourceAttr(resourceByName, "name", prefixListName),
resource.TestCheckResourceAttr(resourceByName, "owner_id", "AWS"),
resource.TestCheckResourceAttr(resourceByName, "address_family", "IPv4"),
resource.TestCheckResourceAttrPtr(resourceByName, "arn", &prefixListArn),
resource.TestCheckResourceAttr(resourceByName, "max_entries", "0"),
resource.TestCheckResourceAttr(resourceByName, "version", "0"),
resource.TestCheckResourceAttr(resourceByName, "tags.%", "0"),

resource.TestCheckResourceAttrPtr(resourceById, "id", &prefixListId),
resource.TestCheckResourceAttr(resourceById, "name", prefixListName),

resource.TestCheckResourceAttrPair(resourceByName, "id", prefixListResourceName, "id"),
resource.TestCheckResourceAttrPair(resourceByName, "name", prefixListResourceName, "name"),
resource.TestCheckResourceAttrPair(resourceByName, "entries.#", prefixListResourceName, "cidr_blocks.#"),
),
},
},
})
}

const testAccDataSourceAwsEc2ManagedPrefixListConfig_basic = `
data "aws_region" "current" {}

data "aws_ec2_managed_prefix_list" "s3_by_name" {
name = "com.amazonaws.${data.aws_region.current.name}.s3"
}

data "aws_ec2_managed_prefix_list" "s3_by_id" {
id = data.aws_ec2_managed_prefix_list.s3_by_name.id
}

data "aws_prefix_list" "s3_by_id" {
prefix_list_id = data.aws_ec2_managed_prefix_list.s3_by_name.id
}
`

func TestAccDataSourceAwsEc2ManagedPrefixList_filter(t *testing.T) {
prefixListName := fmt.Sprintf("com.amazonaws.%s.s3", testAccGetRegion())
prefixListId := ""
prefixListArn := ""

resourceByName := "data.aws_ec2_managed_prefix_list.s3_by_name"
resourceById := "data.aws_ec2_managed_prefix_list.s3_by_id"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceAwsEc2ManagedPrefixListConfig_filter,
Check: resource.ComposeTestCheckFunc(
testAccDataSourceAwsEc2ManagedPrefixListGetIdByName(prefixListName, &prefixListId, &prefixListArn),
resource.TestCheckResourceAttrPtr(resourceByName, "id", &prefixListId),
resource.TestCheckResourceAttr(resourceByName, "name", prefixListName),
resource.TestCheckResourceAttr(resourceByName, "owner_id", "AWS"),
resource.TestCheckResourceAttr(resourceByName, "address_family", "IPv4"),
resource.TestCheckResourceAttrPtr(resourceByName, "arn", &prefixListArn),
resource.TestCheckResourceAttr(resourceByName, "max_entries", "0"),
resource.TestCheckResourceAttr(resourceByName, "version", "0"),
resource.TestCheckResourceAttr(resourceByName, "tags.%", "0"),

resource.TestCheckResourceAttrPair(resourceByName, "id", resourceById, "id"),
resource.TestCheckResourceAttrPair(resourceByName, "name", resourceById, "name"),
resource.TestCheckResourceAttrPair(resourceByName, "entries", resourceById, "entries"),
resource.TestCheckResourceAttrPair(resourceByName, "owner_id", resourceById, "owner_id"),
resource.TestCheckResourceAttrPair(resourceByName, "address_family", resourceById, "address_family"),
resource.TestCheckResourceAttrPair(resourceByName, "arn", resourceById, "arn"),
resource.TestCheckResourceAttrPair(resourceByName, "max_entries", resourceById, "max_entries"),
resource.TestCheckResourceAttrPair(resourceByName, "tags", resourceById, "tags"),
resource.TestCheckResourceAttrPair(resourceByName, "version", resourceById, "version"),
),
},
},
})
}

const testAccDataSourceAwsEc2ManagedPrefixListConfig_filter = `
data "aws_region" "current" {}

data "aws_ec2_managed_prefix_list" "s3_by_name" {
filter {
name = "prefix-list-name"
values = ["com.amazonaws.${data.aws_region.current.name}.s3"]
}
}

data "aws_ec2_managed_prefix_list" "s3_by_id" {
filter {
name = "prefix-list-id"
values = [data.aws_ec2_managed_prefix_list.s3_by_name.id]
}
}
`

func TestAccDataSourceAwsEc2ManagedPrefixList_matchesTooMany(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceAwsPrefixListConfig_matchesTooMany,
ExpectError: regexp.MustCompile(`more than 1 prefix list matched the given criteria`),
},
},
})
}

const testAccDataSourceAwsPrefixListConfig_matchesTooMany = `
data "aws_ec2_managed_prefix_list" "test" {}
`
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ func Provider() *schema.Provider {
"aws_ec2_local_gateway_virtual_interface": dataSourceAwsEc2LocalGatewayVirtualInterface(),
"aws_ec2_local_gateway_virtual_interface_group": dataSourceAwsEc2LocalGatewayVirtualInterfaceGroup(),
"aws_ec2_local_gateway_virtual_interface_groups": dataSourceAwsEc2LocalGatewayVirtualInterfaceGroups(),
"aws_ec2_managed_prefix_list": dataSourceAwsEc2ManagedPrefixList(),
"aws_ec2_spot_price": dataSourceAwsEc2SpotPrice(),
"aws_ec2_transit_gateway": dataSourceAwsEc2TransitGateway(),
"aws_ec2_transit_gateway_dx_gateway_attachment": dataSourceAwsEc2TransitGatewayDxGatewayAttachment(),
Expand Down
Loading