Home > database >  Passing Pulumi S3 Bucket ID to AWS Lambda as a parameter
Passing Pulumi S3 Bucket ID to AWS Lambda as a parameter

Time:12-28

I would like to pass the S3 bucket ID as a parameter to AWS Lambda via Pulumi. However, Pulumi passes this parameter On Build, so I obtain an Object reference in Lambda instead of the S3 path.

My code looks like this

bucket = s3.Bucket(resource_name="bucket", acl="private")
lambda_func = lambda_.Function("Function",
                               role=lambda_role.arn,
                               package_type="Image",
                               image_uri=docker.image_name,
                               image_config={"commands": ["api/main.handler"]},
                               vpc_config={"subnet_ids": private_subnet_ids,
                                           "security_group_ids": [internet_access.id],
                                          },
                               environment=lambda_.FunctionEnvironmentArgs(
                                               variables={"STORE_PATH": f"s3://s{bucket.id}/api"})
                               )

According to Pulumi documentation:

Outputs that contain strings cannot be used directly in operations such as string concatenation.

So I've tried the recommended methods like:

bucket_url = Output.all(bucket.id).apply(lambda l: f"http://{l[0]}/")

Or

url = Output.concat("http://", bucket.id, "/")

Any help is welcomed. Thank you in advance to everyone.

CodePudding user response:

The last method should work fine. Note that bucket.id is just the name of the bucket, you need to build S3 access URL with it, e.g.

url = Output.concat("https://", bucket.id, ".s3.us-west-2.amazonaws.com")
# or url = Output.concat("s3://", bucket.id)

If this still doesn't do what you want, you could export the value of the url to see how it's wrong (or post the result to your question).

export('url', url)

CodePudding user response:

This happens because the environment variables field of the lambda function needs a string. We need to tell Pulumi to ensure that the bucket id has resolved (ie, the bucket is finish creating and the outputs have been returned)

If you pass the Output.concat to the lambda function like so, it works:

lambda_func = aws.lambda_.Function(
    "function",
    runtime="python3.7",
    role=role.arn,
    handler="hello_world.handler",
    code=pulumi.AssetArchive({".": pulumi.FileArchive(".")}),
    environment=aws.lambda_.FunctionEnvironmentArgs(
        variables={"STORE_PATH": pulumi.Output.concat("s3://", bucket.id, "/")}
    ),
)
  • Related