1

The docs for iterators demonstrate how to create several s3 buckets:

import { s3 } from "@cdktf/provider-aws";
import { TerraformIterator, TerraformVariable } from "cdktf";

const list = new TerraformVariable(this, "list", {
  type: "list(string)",
});

const iterator = TerraformIterator.fromList(list.listValue);

const s3Bucket = new s3.Bucket(this, "bucket", {
  forEach: iterator,
  name: iterator.value,
});

How can I then iterate over all of these s3 buckets? As a contrived example, suppose I want to create an EC2 instance for each bucket and pass the bucket ID as an environment variable to it's respective EC2 instance, how can I do that? From what I can tell, s3Bucket itself isn't iterable, does it expose a property that allows users to iterate?

As a more concrete example, I create a number of subnets like so:

    const dataAwsAvailabilityZonesAll =
      new aws.datasources.DataAwsAvailabilityZones(this, "all", {});
    const zoneNames = TerraformIterator.fromList(dataAwsAvailabilityZonesAll.names)


    new aws.vpc.Subnet(this, "priv_subnet", {
      forEach: zoneNames,
      availabilityZone: zoneNames.value,
      cidrBlock: Fn.cidrsubnet(clusterVpc.cidrBlock, 8, Fn.index(dataAwsAvailabilityZonesAll.names, zoneNames.value) + dataAwsAvailabilityZonesAll.names.length),
      mapPublicIpOnLaunch: false,
      vpcId: "${aws_vpc.vpc.id}",
    });

and now I want to make a route table association

    const privateRouteTable = new aws.vpc.RouteTable(
      this,
      "privateRouteTable",
      {
        vpcId: clusterVpc.id,
        route: [
          {
            cidrBlock: "0.0.0.0/0",
            natGatewayId: natGateway.id,
          },
        ],
        tags: {
          name: `privateRouteTable-${environment}`,
        },
      }
    );

    const awsRouteTableAssociationPrivate = new aws.vpc.RouteTableAssociation(
      this,
      "private",
      {
        routeTableId: privateRouteTable.id,
        subnetId:        // <---------- how do I fill this in? I need to somehow iterate over each subnet created earlier
      }
    );

but I'm not sure how to add the ID of each subnet in priv_subnet to awsRouteTableAssociationPrivate

Paymahn Moghadasian
  • 9,301
  • 13
  • 56
  • 94
  • 1
    Can you do something like `forEach: Subnet` in the `awsRouteTableAssociationPrivate` variable and use `subnetId: Subnet.value`? – Marko E Aug 13 '22 at 07:26
  • 2
    No, he can't do something like that, because CDKTF lacks of support for iterating over multiple resources: https://discuss.hashicorp.com/t/how-to-iterate-over-objects-made-with-an-iterator/43115 – Ervin Szilagyi Aug 13 '22 at 11:10

1 Answers1

1

This is currently (0.15.0) not supported, this issue tracks the work on this topic.

Daniel Schmidt
  • 11,605
  • 5
  • 38
  • 70