Skip to content

Commit

Permalink
Merge pull request #28303 from Mongey/cm-db-instances
Browse files Browse the repository at this point in the history
Add aws_db_instances data source
  • Loading branch information
ewbankkit committed Dec 13, 2022
2 parents 157b591 + 2cf15ba commit 42d6731
Show file tree
Hide file tree
Showing 5 changed files with 209 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .changelog/28303.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-data-source
aws_db_instances
```
1 change: 1 addition & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,7 @@ func New(_ context.Context) (*schema.Provider, error) {
"aws_db_cluster_snapshot": rds.DataSourceClusterSnapshot(),
"aws_db_event_categories": rds.DataSourceEventCategories(),
"aws_db_instance": rds.DataSourceInstance(),
"aws_db_instances": rds.DataSourceInstances(),
"aws_db_proxy": rds.DataSourceProxy(),
"aws_db_snapshot": rds.DataSourceSnapshot(),
"aws_db_subnet_group": rds.DataSourceSubnetGroup(),
Expand Down
78 changes: 78 additions & 0 deletions internal/service/rds/instances_data_source.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package rds

import (
"context"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/rds"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/create"
"github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters"
"github.com/hashicorp/terraform-provider-aws/names"
)

func DataSourceInstances() *schema.Resource {
return &schema.Resource{
ReadWithoutTimeout: dataSourceInstancesRead,

Schema: map[string]*schema.Schema{
"instance_arns": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instance_identifiers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"filter": namevaluesfilters.Schema(),
},
}
}

const (
DSNameInstances = "Instances Data Source"
)

func dataSourceInstancesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).RDSConn

input := &rds.DescribeDBInstancesInput{}

if v, ok := d.GetOk("filter"); ok {
input.Filters = namevaluesfilters.New(v.(*schema.Set)).RDSFilters()
}

var instanceARNS []string
var instanceIdentifiers []string

err := conn.DescribeDBInstancesPagesWithContext(ctx, input, func(page *rds.DescribeDBInstancesOutput, lastPage bool) bool {
if page == nil {
return !lastPage
}

for _, dbInstance := range page.DBInstances {
if dbInstance == nil {
continue
}

instanceARNS = append(instanceARNS, aws.StringValue(dbInstance.DBInstanceArn))
instanceIdentifiers = append(instanceIdentifiers, aws.StringValue(dbInstance.DBInstanceIdentifier))
}

return !lastPage
})

if err != nil {
return create.DiagError(names.RDS, create.ErrActionReading, DSNameInstances, "", err)
}

d.SetId(meta.(*conns.AWSClient).Region)
d.Set("instance_arns", instanceARNS)
d.Set("instance_identifiers", instanceIdentifiers)

return nil
}
83 changes: 83 additions & 0 deletions internal/service/rds/instances_data_source_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package rds_test

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/service/rds"
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 TestAccRDSInstancesDataSource_filter(t *testing.T) {
var dbInstance rds.DBInstance
rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)
dataSourceName := "data.aws_db_instances.test"
resourceName := "aws_db_instance.test"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, rds.EndpointsID),
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
CheckDestroy: testAccCheckInstanceDestroy,
Steps: []resource.TestStep{
{
Config: testAccInstancesDataSourceConfig_filter(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckInstanceExists(resourceName, &dbInstance),
resource.TestCheckResourceAttr(dataSourceName, "instance_arns.#", "1"),
resource.TestCheckResourceAttrPair(dataSourceName, "instance_arns.0", resourceName, "arn"),
resource.TestCheckResourceAttr(dataSourceName, "instance_identifiers.#", "1"),
resource.TestCheckResourceAttrPair(dataSourceName, "instance_identifiers.0", resourceName, "identifier"),
),
},
},
})
}

func testAccInstancesDataSourceConfig_filter(rName string) string {
return fmt.Sprintf(`
data "aws_rds_engine_version" "default" {
engine = "postgres"
}
resource "aws_db_instance" "test" {
identifier = %[1]q
allocated_storage = 10
engine = data.aws_rds_engine_version.default.engine
engine_version = data.aws_rds_engine_version.default.version
instance_class = "db.t4g.micro"
db_name = "test"
password = "avoid-plaintext-passwords"
username = "tfacctest"
parameter_group_name = "default.${data.aws_rds_engine_version.default.parameter_group_family}"
skip_final_snapshot = true
apply_immediately = true
}
resource "aws_db_instance" "wrong" {
identifier = "wrong-%[1]s"
allocated_storage = 10
engine = data.aws_rds_engine_version.default.engine
engine_version = data.aws_rds_engine_version.default.version
instance_class = "db.t4g.micro"
db_name = "test"
password = "avoid-plaintext-passwords"
username = "tfacctest"
parameter_group_name = "default.${data.aws_rds_engine_version.default.parameter_group_family}"
skip_final_snapshot = true
apply_immediately = true
}
data "aws_db_instances" "test" {
filter {
name = "db-instance-id"
values = [aws_db_instance.test.identifier]
}
}
`, rName)
}
44 changes: 44 additions & 0 deletions website/docs/d/db_instances.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
subcategory: "RDS (Relational Database)"
layout: "aws"
page_title: "AWS: aws_db_instances"
description: |-
Terraform data source for listing RDS Database Instances.
---

# Data Source: aws_db_instances

Terraform data source for listing RDS Database Instances.

## Example Usage

### Basic Usage

```terraform
data "aws_db_instances" "example" {
filter {
name = "db-instance-id"
values = ["my-database-id"]
}
}
```

## Argument Reference

The following arguments are optional:

* `filter` - (Optional) Configuration block(s) for filtering. Detailed below.

### filter Configuration block

The following arguments are supported by the `filter` configuration block:

* `name` - (Required) Name of the filter field. Valid values can be found in the [RDS DescribeDBClusters API Reference](https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DescribeDBClusters.html).
* `values` - (Required) Set of values that are accepted for the given filter field. Results will be selected if any given value matches.

## Attributes Reference

In addition to all arguments above, the following attributes are exported:

* `instance_arns` - ARNs of the matched RDS instances.
* `instance_identifiers` - Identifiers of the matched RDS instances.

0 comments on commit 42d6731

Please sign in to comment.