How Do I Create a Top-Level Async Function in Pulumi in TypeScript
Introduction
Creating a top-level async function in Pulumi using TypeScript is a common practice to handle asynchronous operations, such as creating resources or fetching data. This approach allows you to use the await
keyword directly at the top level of your Pulumi program, making the code more readable and maintainable.
Step-by-Step Explanation
Step 1: Install Dependencies
Ensure you have the necessary dependencies installed. You need Pulumi and the AWS SDK for Pulumi.
npm install @pulumi/pulumi @pulumi/aws
Step 2: Create a Pulumi Program
Create a new Pulumi program and initialize it with TypeScript.
pulumi new aws-typescript
Step 3: Write the Top-Level Async Function
In your index.ts
file, you can define a top-level async function as follows:
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
(async () => {
// Your async code here
const bucket = new aws.s3.Bucket("my-bucket");
const bucketName = await bucket.id;
console.log(`Bucket name: ${bucketName}`);
})();
Step 4: Deploy the Stack
Run the following command to deploy your stack:
pulumi up
Summary
By wrapping your Pulumi code in an immediately invoked async function, you can use the await
keyword at the top level. This makes it easier to work with asynchronous operations, such as creating resources or fetching data. This approach is particularly useful in Pulumi programs where you need to handle asynchronous tasks efficiently.
Full Code Example
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
(async () => {
// Your async code here
const bucket = new aws.s3.Bucket("my-bucket");
const bucketName = await bucket.id;
console.log(\`Bucket name: \${bucketName}\`);
// Export the bucket name
(global as any).bucketName = bucket.id;
})();
// Export the bucket name
export const bucketName = pulumi.output((global as any).bucketName);
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.