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_elasticache_subnet_group #27233

Merged
merged 17 commits into from
Oct 17, 2022
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
3 changes: 3 additions & 0 deletions .changelog/27233.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-data-source
aws_elasticache_subnet_group
```
1 change: 1 addition & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,7 @@ func New(_ context.Context) (*schema.Provider, error) {

"aws_elasticache_cluster": elasticache.DataSourceCluster(),
"aws_elasticache_replication_group": elasticache.DataSourceReplicationGroup(),
"aws_elasticache_subnet_group": elasticache.DataSourceSubnetGroup(),
"aws_elasticache_user": elasticache.DataSourceUser(),

"aws_elastic_beanstalk_application": elasticbeanstalk.DataSourceApplication(),
Expand Down
29 changes: 29 additions & 0 deletions internal/service/elasticache/find.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,32 @@ func FindParameterGroupByName(conn *elasticache.ElastiCache, name string) (*elas
return nil, tfresource.NewTooManyResultsError(count, input)
}
}

func FindCacheSubnetGroupByName(conn *elasticache.ElastiCache, name string) (*elasticache.CacheSubnetGroup, error) {
input := elasticache.DescribeCacheSubnetGroupsInput{
CacheSubnetGroupName: aws.String(name),
}

output, err := conn.DescribeCacheSubnetGroups(&input)

if tfawserr.ErrCodeEquals(err, elasticache.ErrCodeCacheSubnetGroupNotFoundFault) {
return nil, &resource.NotFoundError{
LastError: err,
LastRequest: input,
}
}

if err != nil {
return nil, err
}

if output == nil || len(output.CacheSubnetGroups) == 0 || output.CacheSubnetGroups[0] == nil {
return nil, tfresource.NewEmptyResultError(input)
}

if count := len(output.CacheSubnetGroups); count > 1 {
return nil, tfresource.NewTooManyResultsError(count, input)
}

return output.CacheSubnetGroups[0], nil
}
47 changes: 15 additions & 32 deletions internal/service/elasticache/subnet_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ func ResourceSubnetGroup() *schema.Resource {
},

Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
Expand All @@ -53,10 +57,6 @@ func ResourceSubnetGroup() *schema.Resource {
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"tags": tftags.TagsSchema(),
"tags_all": tftags.TagsSchemaComputed(),
},
Expand Down Expand Up @@ -142,44 +142,27 @@ func resourceSubnetGroupRead(d *schema.ResourceData, meta interface{}) error {
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig

req := &elasticache.DescribeCacheSubnetGroupsInput{
CacheSubnetGroupName: aws.String(d.Get("name").(string)),
}
group, err := FindCacheSubnetGroupByName(conn, d.Id())

res, err := conn.DescribeCacheSubnetGroups(req)
if err != nil {
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "CacheSubnetGroupNotFoundFault" {
// Update state to indicate the db subnet no longer exists.
log.Printf("[WARN] ElastiCache Subnet Group (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
return err
}
if len(res.CacheSubnetGroups) == 0 {
return fmt.Errorf("Error missing %v", d.Get("name"))
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] ElastiCache Subnet Group (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}

var group *elasticache.CacheSubnetGroup
for _, g := range res.CacheSubnetGroups {
log.Printf("[DEBUG] %v %v", g.CacheSubnetGroupName, d.Id())
if aws.StringValue(g.CacheSubnetGroupName) == d.Id() {
group = g
}
}
if group == nil {
return fmt.Errorf("Error retrieving cache subnet group: %v", res)
if err != nil {
return fmt.Errorf("reading ElastiCache Subnet Group (%s): %w", d.Id(), err)
}

ids := make([]string, len(group.Subnets))
for i, s := range group.Subnets {
ids[i] = aws.StringValue(s.SubnetIdentifier)
var subnetIds []*string
for _, subnet := range group.Subnets {
subnetIds = append(subnetIds, subnet.SubnetIdentifier)
}

d.Set("arn", group.ARN)
d.Set("name", group.CacheSubnetGroupName)
d.Set("description", group.CacheSubnetGroupDescription)
d.Set("subnet_ids", ids)
d.Set("subnet_ids", subnetIds)

tags, err := ListTags(conn, d.Get("arn").(string))

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

import (
"fmt"

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

func DataSourceSubnetGroup() *schema.Resource {
return &schema.Resource{
Read: dataSourceSubnetGroupRead,

Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Required: true,
},
"subnet_ids": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"tags": tftags.TagsSchema(),
},
}
}

func dataSourceSubnetGroupRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).ElastiCacheConn
ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig

name := d.Get("name").(string)

group, err := FindCacheSubnetGroupByName(conn, name)

if err != nil {
return fmt.Errorf("reading ElastiCache Subnet Group (%s): %w", name, err)
}

d.SetId(aws.StringValue(group.CacheSubnetGroupName))

var subnetIds []*string
for _, subnet := range group.Subnets {
subnetIds = append(subnetIds, subnet.SubnetIdentifier)
}

d.Set("arn", group.ARN)
d.Set("description", group.CacheSubnetGroupDescription)
d.Set("subnet_ids", flex.FlattenStringSet(subnetIds))
d.Set("name", group.CacheSubnetGroupName)

tags, err := ListTags(conn, d.Get("arn").(string))

if err != nil {
return fmt.Errorf("listing tags for ElastiCache Subnet Group (%s): %w", d.Id(), err)
}

if err := d.Set("tags", tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil {
return fmt.Errorf("setting tags: %w", err)
}

return nil
}
59 changes: 59 additions & 0 deletions internal/service/elasticache/subnet_group_data_source_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package elasticache_test

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/service/elasticache"
sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-provider-aws/internal/acctest"
)

func testAccPreCheck(t *testing.T) {
if got, want := acctest.Partition(), endpoints.AwsUsGovPartitionID; got == want {
t.Skipf("ElastiCache is not supported in %s partition", got)
}
}

func TestAccElastiCacheSubnetGroupDataSource_basic(t *testing.T) {
rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)
resourceName := "aws_elasticache_subnet_group.test"
dataSourceName := "data.aws_elasticache_subnet_group.test"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, elasticache.EndpointsID),
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
Steps: []resource.TestStep{
{
Config: testAccSubnetGroupDataSourceConfig_basic(rName),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"),
resource.TestCheckResourceAttrPair(dataSourceName, "description", resourceName, "description"),
resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"),
resource.TestCheckResourceAttrPair(dataSourceName, "subnet_ids.#", resourceName, "subnet_ids.#"),
resource.TestCheckResourceAttrPair(dataSourceName, "tags.%", resourceName, "tags.%"),
),
},
},
})
}

func testAccSubnetGroupDataSourceConfig_basic(rName string) string {
return acctest.ConfigCompose(acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(`
resource "aws_elasticache_subnet_group" "test" {
name = %[1]q
subnet_ids = aws_subnet.test.*.id

tags = {
Name = %[1]q
}
}

data "aws_elasticache_subnet_group" "test" {
name = aws_elasticache_subnet_group.test.name
}
`, rName))
}
Loading