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

d/aws_route53_zone: support attribute-only search #39671

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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/39671.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:enhancement
data-source/aws_route53_zone: Support attribute-only filtering
```
111 changes: 78 additions & 33 deletions internal/service/route53/zone_data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,41 +85,88 @@ func dataSourceZone() *schema.Resource {
}

func dataSourceZoneRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
var (
diags diag.Diagnostics
zoneID, name, vpcID string
privateZone bool
)

conn := meta.(*conns.AWSClient).Route53Client(ctx)
ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig

name := d.Get(names.AttrName).(string)
zoneID, zoneIDExists := d.GetOk("zone_id")
vpcID, vpcIDExists := d.GetOk(names.AttrVPCID)
zoneIDArg, zoneIDSet := d.GetOk("zone_id")
if zoneIDSet {
zoneID = zoneIDArg.(string)
}

nameArg, nameSet := d.GetOk(names.AttrName)
if nameSet {
name = nameArg.(string)
}

if zoneIDSet && nameSet {
return sdkdiag.AppendErrorf(diags, "only one of `zone_id` or `name` may be set")
}

vpcIDArg, vpcIDSet := d.GetOk(names.AttrVPCID)
if vpcIDSet {
vpcID = vpcIDArg.(string)
privateZone = true
}

privateZoneArg, privateZoneSet := d.GetOk("private_zone")
if privateZoneSet {
privateZone = privateZoneArg.(bool)
}

if vpcIDSet && !privateZone {
return sdkdiag.AppendErrorf(diags, "`vpc_id` can only be set for private zones")
}

tags := tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{})).IgnoreAWS()

input := &route53.ListHostedZonesInput{}
var hostedZones []awstypes.HostedZone
pages := route53.NewListHostedZonesPaginator(conn, input)
for pages.HasMorePages() {
page, err := pages.NextPage(ctx)
var hostedZone *awstypes.HostedZone

if zoneIDSet {
// Perform direct lookup on unique zoneID
foundZone, err := findHostedZoneByID(ctx, conn, zoneID)
if err != nil {
return sdkdiag.AppendErrorf(diags, "reading Route 53 Hosted Zones: %s", err)
return sdkdiag.AppendFromErr(diags, err)
}
hostedZone = foundZone.HostedZone
} else {
// As name is not unique, we need to list all zones and filter
var hostedZones []awstypes.HostedZone
input := &route53.ListHostedZonesInput{}
pages := route53.NewListHostedZonesPaginator(conn, input)
for pages.HasMorePages() {
page, err := pages.NextPage(ctx)
if err != nil {
return sdkdiag.AppendErrorf(diags, "reading Route 53 Hosted Zones: %s", err)
}

for _, hostedZone := range page.HostedZones {
hostedZoneID := cleanZoneID(aws.ToString(hostedZone.Id))
if zoneIDExists && hostedZoneID == zoneID.(string) {
hostedZones = append(hostedZones, hostedZone)
// we check if the name is the same as requested and if private zone field is the same as requested or if there is a vpc_id
} else if (normalizeZoneName(aws.ToString(hostedZone.Name)) == normalizeZoneName(name)) && (hostedZone.Config.PrivateZone == d.Get("private_zone").(bool) || (hostedZone.Config.PrivateZone && vpcIDExists)) {
matchingVPC := false
if vpcIDExists {
hostedZone, err := findHostedZoneByID(ctx, conn, hostedZoneID)
for _, zone := range page.HostedZones {
// skip zone on explicit name mismatch
if nameSet && (normalizeZoneName(aws.ToString(zone.Name)) != normalizeZoneName(name)) {
continue
}

// skip zone on type mismatch
if zone.Config.PrivateZone != privateZone {
continue
}

zoneID := cleanZoneID(aws.ToString(zone.Id))

matchingVPC := false
if vpcIDSet {
zoneDetails, err := findHostedZoneByID(ctx, conn, zoneID)
if err != nil {
return sdkdiag.AppendErrorf(diags, "reading Route 53 Hosted Zone (%s): %s", hostedZoneID, err)
return sdkdiag.AppendErrorf(diags, "reading Route 53 Hosted Zone (%s): %s", zoneID, err)
}

for _, v := range hostedZone.VPCs {
if aws.ToString(v.VPCId) == vpcID.(string) {
for _, v := range zoneDetails.VPCs {
if aws.ToString(v.VPCId) == vpcID {
matchingVPC = true
break
}
Expand All @@ -130,26 +177,24 @@ func dataSourceZoneRead(ctx context.Context, d *schema.ResourceData, meta interf

matchingTags := true
if len(tags) > 0 {
output, err := listTags(ctx, conn, hostedZoneID, string(awstypes.TagResourceTypeHostedzone))

zoneTags, err := listTags(ctx, conn, zoneID, string(awstypes.TagResourceTypeHostedzone))
if err != nil {
return sdkdiag.AppendErrorf(diags, "listing Route 53 Hosted Zone (%s) tags: %s", hostedZoneID, err)
return sdkdiag.AppendErrorf(diags, "listing Route 53 Hosted Zone (%s) tags: %s", zoneID, err)
}

matchingTags = output.ContainsAll(tags)
matchingTags = zoneTags.ContainsAll(tags)
}

if matchingTags && matchingVPC {
hostedZones = append(hostedZones, hostedZone)
hostedZones = append(hostedZones, zone)
}
}
}
}

hostedZone, err := tfresource.AssertSingleValueResult(hostedZones)

if err != nil {
return sdkdiag.AppendFromErr(diags, tfresource.SingularDataSourceFindError("Route 53 Hosted Zone", err))
var err error
hostedZone, err = tfresource.AssertSingleValueResult(hostedZones)
if err != nil {
return sdkdiag.AppendFromErr(diags, tfresource.SingularDataSourceFindError("Route 53 Hosted Zone", err))
}
}

hostedZoneID := cleanZoneID(aws.ToString(hostedZone.Id))
Expand Down
50 changes: 50 additions & 0 deletions internal/service/route53/zone_data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,34 @@ func TestAccRoute53ZoneDataSource_tags(t *testing.T) {
})
}

func TestAccRoute53ZoneDataSource_tagsOnly(t *testing.T) {
ctx := acctest.Context(t)
rInt := sdkacctest.RandInt()
resourceName := "aws_route53_zone.test"
dataSourceName := "data.aws_route53_zone.test"

fqdn := acctest.RandomFQDomainName()

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(ctx, t) },
ErrorCheck: acctest.ErrorCheck(t, names.Route53ServiceID),
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
CheckDestroy: testAccCheckZoneDestroy(ctx),
Steps: []resource.TestStep{
{
Config: testAccZoneDataSourceConfig_tagsOnly(fqdn, rInt),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrPair(resourceName, names.AttrID, dataSourceName, names.AttrID),
resource.TestCheckResourceAttrPair(resourceName, names.AttrName, dataSourceName, names.AttrName),
resource.TestCheckResourceAttrPair(resourceName, "name_servers.#", dataSourceName, "name_servers.#"),
resource.TestCheckResourceAttrPair(resourceName, "primary_name_server", dataSourceName, "primary_name_server"),
resource.TestCheckResourceAttrPair(resourceName, names.AttrTags, dataSourceName, names.AttrTags),
),
},
},
})
}

func TestAccRoute53ZoneDataSource_vpc(t *testing.T) {
ctx := acctest.Context(t)
rInt := sdkacctest.RandInt()
Expand Down Expand Up @@ -248,6 +276,28 @@ data "aws_route53_zone" "test" {
`, fqdn, rInt)
}

func testAccZoneDataSourceConfig_tagsOnly(fqdn string, rInt int) string {
return fmt.Sprintf(`
resource "aws_route53_zone" "test" {
name = %[1]q

tags = {
Environment = "tf-acc-test-%[2]d"
Name = "tf-acc-test-%[2]d"
}
}

data "aws_route53_zone" "test" {
tags = {
Environment = "tf-acc-test-%[2]d"
Name = "tf-acc-test-%[2]d"
}

depends_on = [aws_route53_zone.test]
}
`, fqdn, rInt)
}

func testAccZoneDataSourceConfig_vpc(rInt int) string {
return fmt.Sprintf(`
resource "aws_vpc" "test" {
Expand Down
33 changes: 25 additions & 8 deletions website/docs/d/route53_zone.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,34 @@ resource "aws_route53_record" "www" {
}
```

The following example shows how to get a Hosted Zone from a unique combination of its tags:

```terraform
data "aws_route53_zone" "selected" {
tags {
scope = "local"
category = "api"
}
}

output "local_api_zone" {
value = data.aws_route53_zone.selected.zone_id
}
```

## Argument Reference

The arguments of this data source act as filters for querying the available
Hosted Zone. You have to use `zone_id` or `name`, not both of them. The given filter must match exactly one
Hosted Zone. If you use `name` field for private Hosted Zone, you need to add `private_zone` field to `true`.
Hosted Zone.
The `zone_id` and `name` arguments are mutually exclusive: only one can be specified.
The `private_zone`, `vpc_id` and `tags` filters are ignored when `zone_id` is
specified, and together they must filter to match exactly one Hosted Zone.

* `zone_id` - (Optional) Hosted Zone id of the desired Hosted Zone.
* `name` - (Optional) Hosted Zone name of the desired Hosted Zone.
* `private_zone` - (Optional) Used with `name` field to get a private Hosted Zone.
* `vpc_id` - (Optional) Used with `name` field to get a private Hosted Zone associated with the vpc_id (in this case, private_zone is not mandatory).
* `tags` - (Optional) Used with `name` field. A map of tags, each pair of which must exactly match a pair on the desired Hosted Zone.
* `zone_id` - (Optional) Directly return the Hosted Zone with the specified Zone ID. No further filtering is performed.
* `name` - (Optional) Hosted Zone name of the desired Hosted Zone. If blank, then accept any name, filtering on only `private_zone`, `vpc_id` and `tags`.
* `private_zone` - (Optional) Filter to only private Hosted Zones.
* `vpc_id` - (Optional, string) Filter to private Hosted Zones associated with the specified `vpc_id`.
* `tags` - (Optional) A map of tags, each pair of which must exactly match a pair on the desired Hosted Zone.

## Attribute Reference

Expand All @@ -50,7 +67,7 @@ result attributes. This data source will complete the data by populating
any fields that are not included in the configuration with the data for
the selected Hosted Zone.

The following attribute is additionally exported:
The following attributes are additionally exported:

* `arn` - ARN of the Hosted Zone.
* `caller_reference` - Caller Reference of the Hosted Zone.
Expand Down