1. How to iterate over a list of Outputs to create resources?

    TypeScript

    Iterating over a list of outputs to create resources involves using the apply method. This method allows us to perform computations on the output's underlying value in the context of a promise chain. It is essentially the promise .then(), but it understands outputs and can be used inside resources.

    Here we are going to create multiple AWS S3 buckets using a list of names stored in an Output. In this case, we will have an output that returns an array of bucket names, and we will iterate over this array to create new S3 buckets for each of those names.

    import * as pulumi from "@pulumi/pulumi"; import * as aws from "@pulumi/aws"; // Let's assume that the bucket_names_output is an output that returns an array of bucket names. For example: let bucket_names_output = pulumi.output(["bucket1", "bucket2", "bucket3"]); bucket_names_output.apply(bucket_names => { // Here we are iterating over the bucket names bucket_names.forEach(bucket_name => { let new_bucket = new aws.s3.Bucket(bucket_name, {}); }); });

    In the above code:

    • We're using the aws.s3.Bucket resource (AWS S3 Bucket docs) to create the buckets.
    • bucket_names_output.apply allows us to perform operations and transformations on our Output using a callback.
    • Within the callback function, we used Array.prototype.forEach to loop over each bucket name and create a new S3 bucket with that name.

    Remember that because resources are created asynchronously, the order of creation may not exactly match the order of the names in the array.