Is it safe to create new resources inside an apply...
# general
b
Is it safe to create new resources inside an apply? Web searches suggest it might not be at times, especially with preview. However pulumi's own docs do it https://www.pulumi.com/docs/iac/concepts/inputs-outputs/apply/. There's cases particularly with arrays of elements and needing to loop through and create other related resources that I don't see any way around it, unlike some simple cases where it can be avoided.
f
there are caveats about doing this; please see e.g. https://github.com/pulumi/docs/issues/12459
b
Thanks for confirming. It'd be great to get that note added, as well as ideally not showing an example that violates it.
Also seemingly missing, any real world apply usage, dealing with inputs and outputs for a collection of related resources. My current example I don't see any other option but to move to another project and stack and use outputs from prior.
l
I can't see a resource constructor anywhere in those docs you linked. The closest I can see is a policy document in this section: https://www.pulumi.com/docs/iac/concepts/inputs-outputs/apply/#outputs-and-json But that's not a resource.
b
Yes, bucket policy resource, Go example:
Copy code
// IAM Policy Document that allows the Lambda service to write to the S3 bucket
		s3Bucket.Arn.ApplyT(func(arn string) (string, error) {
			policy := fmt.Sprintf(`{
				"Version": "2012-10-17",
				"Statement": [{
					"Effect": "Allow",
					"Principal": {"Service": "<http://lambda.amazonaws.com|lambda.amazonaws.com>"},
					"Action": ["s3:PutObject", "s3:PutObjectAcl"],
					"Resource": "%s/*"
				}]
			}`, arn)

			// Attach the policy to the bucket
			_, err := s3.NewBucketPolicy(ctx, "myBucketPolicy", &s3.BucketPolicyArgs{
				Bucket: s3Bucket.ID(),
				Policy: pulumi.String(policy),
			})
			if err != nil {
				return "", err
			}

			return "", nil
		})
l
And is s3.NewBucketPolicy returning a resource? I note that the TS, JS, Python, C# and Java examples do not return resources, they return JSON strings wrapped in an output.
Yea that example looks different. I don't know golang at all, but it looks like you could make the example like the other ones by returning the policy output string from ApplyT, and creating the policy outside the ApplyT.
b
Looks like the language samples vary, maybe just Go example isn't great, resource is created inside applyt and resource returned discarded empty string returned
l
Yea, that section looks old. I wouldn't recommend using that TS example either, there's a better way to do it via the PolicyDocument string interpolation class.
b
Yes probably, just pointing out that the doc for Go should maybe be adjusted because it's confusing / misleading