Search code examples
pythonoutputpulumi

Object of type Output is not JSON serializable


stack_name = "test-stack"
bucket = aws.s3.Bucket(
    f"{stack_name}",
    acl="private",
)
firehose_s3_policy = aws.iam.Policy(
    f"{stack_name}-firehose-s3-access-policy",
    policy=json.dumps(
        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "s3:*",
                    ],
                    "Resource": [
                        bucket.arn,
                    ]
                }
            ]
        }
    ))

And the error I get:

TypeError: Object of type Output is not JSON serializable

If I make bucket.arn a string (str(bucket.arn)) I get \"Resource\": [\"<pulumi.output.Output object at 0x7f404d2ebed0>\"]

I tried to use apply, but it doesn't work either. How to solve it?


Solution

  • You need to use apply to convert an output of string to an output of JSON:

    def public_read_policy_for_bucket(arn):
        return json.dumps({
            "Version": "2012-10-17",
            "Statement": [{
                "Effect": "Allow",
                "Principal": "*",
                "Action": [
                    "s3:*"
                ],
                "Resource": [
                    arn,
                ]
            }]
        })
    
    firehose_s3_policy = aws.iam.Policy(
        f"{stack_name}-firehose-s3-access-policy",
        policy=bucket.arn.apply(public_read_policy_for_bucket))
    

    See a full example.