Infrastructure as code · Beginner · 17 min
Write your first Pulumi program in TypeScript
By Padding · Updated 18 Nov 2026
Linux or macOS · Node.js 26 · Pulumi 3.278.0 · TypeScript 5.9.3 · @pulumi/random 4.21 · @pulumi/command 1.3
You will install the Pulumi CLI, keep state in a local folder, declare resources in a TypeScript program, preview and apply it, read its outputs, change it and watch the diff, then destroy and remove the stack.
On this page
Pulumi is an infrastructure-as-code tool where you describe resources in an ordinary programming language instead of a configuration language. A Pulumi program in TypeScript is a Node.js script: you create objects such as new random.RandomPet(...), and the Pulumi engine works out what has to be created, changed or deleted to make the real world match. The engine keeps a record of what exists, called state, and compares your program against it on every run.
Most Pulumi guides start with a cloud account and a Pulumi Cloud login. This one needs neither. State lives in a folder on your machine, and the two providers you use, random and command, run locally. Everything you learn carries straight over to AWS, Azure or Google Cloud resources later: only the provider package changes.
By the end you will have:
- the Pulumi CLI 3.278 installed in your home folder
- a stack whose state is stored in
~/pulumi-demo/state, with its encryption passphrase read from a file - a TypeScript program that generates a name and a port, runs a local command with them, and exports outputs
- seen a preview, an update, a diff after a code change, and a full tear-down
All work happens in ~/pulumi-demo, so nothing you already have is touched.
Step 1 · Install the Pulumi CLI
The Pulumi CLI is a single Go binary plus a few language hosts. The official install script puts it in ~/.pulumi/bin and does not need sudo. Pin the version so you get exactly the release this tutorial was written against:
curl -fsSL https://get.pulumi.com | sh -s -- --version 3.278.0
export PATH="$HOME/.pulumi/bin:$PATH"The script also adds ~/.pulumi/bin to the PATH in your shell profile, so new terminals find pulumi too. The export line makes it available in the terminal you have open now.
On macOS you can use Homebrew instead (brew install pulumi/tap/pulumi), which installs the current release rather than a pinned one.
A CLI installed this way gets no updates from your package manager. To upgrade later, run the same command with a newer version number. To remove it, delete ~/.pulumi.
Check it worked
pulumi versionIt prints v3.278.0.
Step 2 · Keep state in a local folder
Pulumi needs somewhere to store state. The default is Pulumi Cloud, which requires an account. A file backend stores the same JSON state files in a folder you choose. Create the demo folder and log in to a backend inside it:
mkdir -p ~/pulumi-demo/state
pulumi login file://~/pulumi-demo/statePulumi expands the ~ itself, so the quotes and $HOME you might expect are not needed here.
Pulumi encrypts secret values in state with a key derived from a passphrase. It reads the passphrase from the PULUMI_CONFIG_PASSPHRASE_FILE environment variable, so it never appears on the command line or in your shell history. Create the file with private permissions from the start, then point Pulumi at it:
(umask 077; head -c 32 /dev/urandom | base64 > ~/pulumi-demo/passphrase.txt)
export PULUMI_CONFIG_PASSPHRASE_FILE="$HOME/pulumi-demo/passphrase.txt"The file sits outside the project folder, so it will not end up in Git when you commit the project. Keep a copy somewhere safe for real projects: without the passphrase, Pulumi cannot decrypt the stack's secrets. Every new terminal needs that export line again, or put it in your shell profile.
Check it worked
pulumi whoami -v
ls -l ~/pulumi-demo/passphrase.txtpulumi whoami -v shows a backend URL that starts with file:// and ends in pulumi-demo/state. The ls line starts with -rw-------: only you can read the passphrase file.
Step 3 · Create a TypeScript project
A Pulumi project is a folder with a Pulumi.yaml file that names the project and its runtime. pulumi new can generate one from a template, but writing the four files yourself shows that there is nothing hidden in them:
mkdir -p ~/pulumi-demo/hello
cd ~/pulumi-demo/hello
cat > Pulumi.yaml <<'YAML'
name: hello-pulumi
description: A first Pulumi program that uses only local providers
runtime: nodejs
YAML
cat > package.json <<'JSON'
{
"name": "hello-pulumi",
"private": true,
"main": "index.ts"
}
JSON
cat > tsconfig.json <<'JSON'
{
"compilerOptions": {
"strict": true,
"target": "es2022",
"module": "nodenext",
"moduleResolution": "nodenext",
"outDir": "bin",
"noImplicitReturns": true
},
"files": ["index.ts"]
}
JSONruntime: nodejs tells the CLI to run the program with Node.js, and "main": "index.ts" tells it which file to start. Pulumi compiles TypeScript on the fly, so there is no build step to run.
Now install the Pulumi SDK, the two provider packages and TypeScript, each at an exact version so a later npm install cannot move them:
npm install --save-exact @pulumi/pulumi@3.278.0 @pulumi/random@4.21.6 @pulumi/command@1.3.0
npm install --save-exact --save-dev typescript@5.9.3 @types/node@26.6.11Finally, create a stack. A stack is one deployed copy of the project, such as dev or prod, each with its own state:
pulumi stack init devWith a file backend the stack uses the passphrase secrets provider, and Pulumi writes a Pulumi.dev.yaml holding the salt for your passphrase. That file is safe to commit; the passphrase is not.
Check it worked
ls
pulumi stack lsThe folder holds Pulumi.yaml, Pulumi.dev.yaml, package.json, package-lock.json, tsconfig.json and node_modules. pulumi stack ls lists one stack, dev, marked with * as the current one.
Step 4 · Declare resources in index.ts
Write the program. It declares three resources and four outputs:
cat > index.ts <<'TS'
import * as pulumi from "@pulumi/pulumi";
import * as random from "@pulumi/random";
import * as command from "@pulumi/command";
// A random two-word name, such as "brave-otter".
const site = new random.RandomPet("site-name", { length: 2 });
// A random port between 8000 and 8999.
const port = new random.RandomInteger("site-port", { min: 8000, max: 8999 });
// A command that runs on this machine when the resource is created.
// The values reach the shell as environment variables, not pasted into the command text.
const announce = new command.local.Command("announce", {
create: 'echo "$SITE_NAME will listen on port $SITE_PORT"',
environment: {
SITE_NAME: site.id,
SITE_PORT: port.result.apply((p) => p.toString()),
},
});
export const siteName = site.id;
export const sitePort = port.result;
export const siteUrl = pulumi.interpolate`http://${site.id}.internal:${port.result}`;
export const announcement = announce.stdout;
TSThree ideas carry the whole of Pulumi:
- Resources are objects. Each
newcall registers a resource with the engine. The first argument is a logical name that must be unique in the stack; Pulumi uses it to track the resource in state. The second is the resource's inputs. - Outputs are promises with extra information.
site.idis not a string. It is anOutput<string>, a value that will exist once the resource has been created. It also records which resource it came from, so Pulumi knowsannouncedepends onsiteandportand must be created after them. You never write that dependency down yourself. - You transform outputs with
applyorpulumi.interpolate.port.result.apply((p) => p.toString())runs the function once the number is known and returns a newOutput<string>.pulumi.interpolateis a template literal that does the same for strings. Writing` `${site.id}`` with a plain template literal would not work: the string would hold a warning message from Pulumi instead of the name.
The export const lines become stack outputs, values Pulumi stores in state and shows after each update.
How this differs from HCL
In Terraform or OpenTofu you write HCL, a declarative language where resource "random_pet" "site" { length = 2 } is configuration, not code. Here the same thing is a constructor call, so loops, functions, if statements, types and npm packages are all available, and your editor checks property names as you type. The model underneath is the same: a desired state, a recorded state, and a plan to close the gap. The price is that a program can do things HCL cannot, such as read files or call APIs while it runs, so keep programs as plain declarations unless you have a reason not to.
Check it worked
Ask the TypeScript compiler to check the program without writing any files:
npx tsc --noEmitIt prints nothing and exits cleanly. Change length: 2 to length: "2" and run it again to see a type error, then change it back.
Step 5 · Preview and apply
pulumi preview runs your program, compares the result with state, and shows what would change, without changing anything:
pulumi previewThe first time it runs, Pulumi downloads the random and command provider plugins and caches them in ~/.pulumi/plugins. Later runs, and other projects that use the same versions, reuse the cache. That helps if you work on metered or prepaid mobile data: the download happens once per provider version, not once per project.
The preview lists the stack itself and the three resources with a + for create, and ends with a summary such as 4 to create. Apply it:
pulumi up --yes--yes skips the confirmation prompt. Leave it out when you work by hand, and Pulumi shows the preview again and asks you to choose yes before it changes anything.
Check it worked
The update ends with an Outputs: block that lists announcement, siteName, sitePort and siteUrl, and a summary of 4 created. The announcement line reads something like brave-otter will listen on port 8412, with your own name and number.
Step 6 · Read the stack outputs
Outputs are how other tools, scripts and stacks get values out of a deployment. List them all, or read one:
pulumi stack output
pulumi stack output siteUrl
pulumi stack output --jsonThe second command prints just the URL, with no quotes or labels, which makes it easy to use in a script, for example curl "$(pulumi stack output siteUrl)" once the address points at something real. --json prints every output as one JSON object, useful with jq or from another program.
State itself is a JSON file under the backend folder. You never edit it by hand, but it helps to see where it lives:
find ~/pulumi-demo/state -name 'dev.json'Check it worked
pulumi stack output siteUrl prints one line in the form http://<two-word-name>.internal:<port>, and find prints a path that ends in stacks/hello-pulumi/dev.json.
Step 7 · Change the code and read the diff
Make the name three words long. Rewrite the line that creates the name. The rest of the file stays the same:
cat > index.ts <<'TS'
import * as pulumi from "@pulumi/pulumi";
import * as random from "@pulumi/random";
import * as command from "@pulumi/command";
// A random three-word name, such as "quietly-brave-otter".
const site = new random.RandomPet("site-name", { length: 3 });
// A random port between 8000 and 8999.
const port = new random.RandomInteger("site-port", { min: 8000, max: 8999 });
// A command that runs on this machine when the resource is created.
// The values reach the shell as environment variables, not pasted into the command text.
const announce = new command.local.Command("announce", {
create: 'echo "$SITE_NAME will listen on port $SITE_PORT"',
environment: {
SITE_NAME: site.id,
SITE_PORT: port.result.apply((p) => p.toString()),
},
});
export const siteName = site.id;
export const sitePort = port.result;
export const siteUrl = pulumi.interpolate`http://${site.id}.internal:${port.result}`;
export const announcement = announce.stdout;
TSPreview again, this time with --diff to see each changed property:
pulumi preview --diffRead it from the top. site-name is marked for replacement (+-), with length changing from 2 to 3: a random name cannot be edited in place, so Pulumi creates a new one and deletes the old one. site-port is not listed as changing, because nothing about it changed. announce changes because its SITE_NAME input depends on the new name, and the preview cannot know that value yet, so it shows it as [unknown]. This chain, where one change ripples through outputs into dependent resources, is the part of a preview to read most carefully on real infrastructure.
Apply the change:
pulumi up --yesCheck it worked
pulumi stack output siteName
pulumi stack output announcementThe name now has three words joined by hyphens, and the announcement uses it, while sitePort keeps the number it had before.
Step 8 · Destroy the stack and clean up
pulumi destroy deletes every resource in the stack, in reverse dependency order, and leaves the stack itself empty. Here that is harmless, but on a cloud account the same command deletes real servers and databases, so always read its preview when you run it by hand. Destroy the resources, then remove the stack and its history:
cd ~/pulumi-demo/hello
pulumi destroy --yes
pulumi stack rm dev --yespulumi stack rm refuses to remove a stack that still has resources, which is why destroy comes first. It also deletes Pulumi.dev.yaml.
Log out of the file backend and delete the demo folder, which holds the project, the state and the passphrase file:
pulumi logout
unset PULUMI_CONFIG_PASSPHRASE_FILE
cd ~
rm -rf ~/pulumi-demoThe unset line stops this terminal pointing Pulumi at a passphrase file that no longer exists. The CLI and the cached plugins in ~/.pulumi stay, ready for the next tutorial. Delete ~/.pulumi if you want them gone too.
Check it worked
pulumi destroy ends with a summary such as 4 deleted, and pulumi stack rm reports that the stack has been removed. Confirm the demo folder is gone:
ls ~/pulumi-demols reports that ~/pulumi-demo does not exist (No such file or directory).
Next steps
- Add more stacks, typed configuration and encrypted secrets to this kind of project: manage Pulumi stacks, configuration and encrypted secrets.
- See the same plan, apply and destroy loop in HCL: manage infrastructure with OpenTofu.
Related tutorials
- Set up a new cloud server on first boot with cloud-init user dataYou will write and validate one cloud-init file that gives a new Ubuntu 26.04 server a key-only sudo user, blocks root login, installs and upgrades packages, writes files with the right owners and runs setup commands once, ready to paste into any provider's user data field.
- Use Terraform workspaces for separate environments, and know when not toYou will run one Terraform configuration as separate dev and staging workspaces with per-environment settings, find where each workspace keeps its state, guard every apply with a workspace check, and compare the result with a directory per environment.
- Test Ansible roles with ansible-lint and MoleculeYou will clean up a role until ansible-lint passes its production profile, then add a Molecule scenario that applies the role, proves a second run changes nothing and checks the result with a verify playbook.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials