Using dynamic blocks to add tags for data source

Hello,

I have this data source and I would like to be able to add a dynamic block that deals with tags, but it seems I can’t find the correct way to do it.

data "aws_route53_zone" "external_zone" {
  name              = var.base_domain
  private_zone = false

  dynamic "tags" {
    for_each = var.hosted_zone_tags
    content {
      name  = tag.key
      values = tag.value
    }
  }
}

The error received is:

Error: Unsupported block type

  on datasources.tf line 43, in data "aws_route53_zone" "external_zone":
  43:   dynamic "tags" {

Blocks of type "tags" are not expected here.

Is there any workaround to achieve this? I need dynamic blocks because using variables I would like to change completely the content (both keys and values) for certain environments.

Thanks,
Ionut

You don’t need dynamic blocks in this case. If you look at the documentation for aws_route53_zone (https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/route53_zone) you can see that the tags is just an optional argument (expecting a map of strings) rather than a block.

So you just need something like:

data "aws_route53_zone" "external_zone" {
  name         = var.base_domain
  private_zone = false
  tags         = var.hosted_zone_tags
}

Indeed! To add some extra context here in case the difference isn’t clear, a dynamic "tags" block like in the original comment would effectively be generating something like this:

data "aws_route53_zone" "external_zone" {
  name         = var.base_domain
  private_zone = false

  tags {
    name   = "Name"
    values = "example"
  }
  tags {
    name   = "Environment"
    values = "production"
  }
}

You only need to use dynamic blocks in situations where the resource type is expecting nested objects represented as nested blocks.

Given the context here and what you put in the content block, I think you might’ve been thinking of filter blocks within the data sources associated with various EC2 object types. EC2 has a different API model than Route53, and so consequently the associated data sources have a different design too, as we can see with aws_ami:

data "aws_ami" "example" {
  executable_users = ["self"]
  most_recent      = true
  name_regex       = "^myami-\\d{3}"
  owners           = ["self"]

  filter {
    name   = "name"
    values = ["myami-*"]
  }
}

In this case it would be appropriate to use a dynamic "filter" block to generate zero or more filter blocks, using a similar syntax to what was in the original example, because in this case the resource type is defined to expect nested objects in this way.

Hello,

Yes it’s true that I took from the example of dynamic filters and I was hoping to achieve the same results but for tags.

Thank you both for the suggestion!