is there an example of using `applyT` in a for loo...
# golang
l
is there an example of using
applyT
in a for loop? I have an array of
s3.Bucket
and want to loop over them to get a an array of strings (of the
Bucket.Arn
) which I'd like to pass as an argument to a component which among other things creates an IAM Policy. I want to use the ARNs array in the policy resource
I'm not even sure this is possible
f
Would something like this help?
Copy code
package main

import (
	"encoding/json"

	"<http://github.com/pulumi/pulumi-aws/sdk/v6/go/aws/iam|github.com/pulumi/pulumi-aws/sdk/v6/go/aws/iam>"
	"<http://github.com/pulumi/pulumi-aws/sdk/v6/go/aws/s3|github.com/pulumi/pulumi-aws/sdk/v6/go/aws/s3>"
	"<http://github.com/pulumi/pulumi/sdk/v3/go/pulumi|github.com/pulumi/pulumi/sdk/v3/go/pulumi>"
)

func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {
		// Create an array of S3 buckets
		buckets := []s3.Bucket{}
		for i := 0; i < 3; i++ {
			bucket, err := s3.NewBucket(ctx, pulumi.Sprintf("my-bucket-%d", i), nil)
			if err != nil {
				return err
			}
			buckets = append(buckets, *bucket)
		}

		// Extract ARNs from the array of buckets using Apply and append them to a new array
		var bucketArns pulumi.StringArray
		for _, bucket := range buckets {
			bucketArn := bucket.Arn.ApplyT(func(arn string) string {
				return arn
			}).(pulumi.StringOutput)
			bucketArns = append(bucketArns, bucketArn)
		}

		// Create IAM Policy using the ARNs array
		policyDocument := pulumi.All(bucketArns...).ApplyT(func(arns []interface{}) (string, error) {
			arnsArray := make([]string, len(arns))
			for i, arn := range arns {
				arnsArray[i] = arn.(string)
			}

			policy := map[string]interface{}{
				"Version": "2012-10-17",
				"Statement": []map[string]interface{}{
					{
						"Effect":   "Allow",
						"Action":   "s3:*",
						"Resource": arnsArray,
					},
				},
			}

			policyJson, err := json.Marshal(policy)
			if err != nil {
				return "", err
			}
			return string(policyJson), nil
		}).(pulumi.StringOutput)

		_, err := iam.NewPolicy(ctx, "bucketPolicy", &iam.PolicyArgs{
			Policy: policyDocument,
		})
		if err != nil {
			return err
		}

		return nil
	})
}
l
Thanks @faint-elephant-30784 I have something similar at the moment but your example looks a bit less complex..
f
No worries.