Skip to content

Resource hooks ​

2025-06-30 · will-jones, julien-poissonnier

Pulumi programs are declarative, allowing you to specify the desired state of your infrastructure while Pulumi figures out the rest. But what about the times where you want to be more involved in what Pulumi is doing? Resource hooks are one of our most requested features, and from Pulumi 3.182.0 we're excited to announce that you'll be able to use them to run arbitrary code at any point in Pulumi's resource lifecycle!

When you run pulumi up, Pulumi runs your program and works out the set of create, update and delete operations required to realise the state it describes. Hooks allow you to attach custom callbacks to these operations, enabling you to execute custom behaviour before or after they occur. You might want to set up an SSH tunnel to a bastion host before Pulumi attempts to create or update a virtual machine or database; or you may wish to send metrics to your data warehouse whenever Pulumi updates certain resources or properties. Hooks allow you to do all this and more -- as with everything else in Pulumi, you are free to make use of the full power of your favourite programming language.

Hooks in action ​

Let's check out the use case of opening a tunnel to a remote host before running a command. For this we'll use a contrived example where we use the socat command to open a local TCP port that forwards to a remote host. Here we'll open localhost:1234 and forward it to example.com:80. We'll then use Pulumi's command provider to invoke curl to make a request to that local port, which will be forwarded to the remote host. To start with, let's write the program without hooks:

typescript
import * as command from "@pulumi/command"

export = async () => {
  const curl = "curl -H'Host: example.com' localhost:1234"

  const cmd = new command.local.Command("curl", {
    create: curl,
    update: curl,
    delete: curl,
    triggers: [new Date().toString()],
  })

  return {
    stdout: cmd.stdout,
  }
}

We set up a local Command that will run the same curl command whether it is being created, updated, or deleted. For the purposes of illustration, we also set the triggers property to the current date and time, so that the command will always be run when we run pulumi up. Let's now do just that:

shell
pulumi up

Assuming we have nothing running on port 1234, we'll get an error such as the following:

Updating (...)

View in Browser (Ctrl+O): https://app.pulumi.com/...

     Type                      Name               Status                  Info
     pulumi:pulumi:Stack       resource-hooks     **failed**              1 error; 9 messages
 ++  └─ command:local:Command  curl               **creating failed**     [diff: ]; 1 error

Diagnostics:
  command:local:Command (curl):
    error: exit status 7: running "curl -H'Host: example.com' localhost:1234":
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
    curl: (7) Failed to connect to localhost port 1234 after 0 ms: Could not connect to server

As expected, nothing is listening on port 1234, so curl fails with an error. Previously, we might have fixed this by using a wrapper around our Pulumi program, such as the Automation API. With resource hooks, however, the solution is at our fingertips! We'll hook into the Command resource's lifecycle to open a tunnel before any operation is run, and to close it afterwards:

typescript
import * as child_process from "child_process"
import * as command from "@pulumi/command"
import * as pulumi from "@pulumi/pulumi"

export = async () => {
  let tunnel: child_process.ChildProcessWithoutNullStreams | undefined

  const beforeHook = new pulumi.ResourceHook("before", async args => {
    console.log("Opening tunnel")

    tunnel = child_process.spawn(
      "socat",
      [
        "TCP-LISTEN:1234,fork",
        "TCP:example.com:80",
      ],
      { detached: true }
    )

    console.log(`Tunnel opened: ${tunnel?.pid}`)
  })

  const afterHook = new pulumi.ResourceHook("after", async args => {
    console.log(`Closing tunnel: ${tunnel?.pid}`)
    tunnel?.kill("SIGKILL")
  })

  const curl = "curl -H'Host: example.com' localhost:1234"

  const cmd = new command.local.Command("curl", {
    create: curl,
    update: curl,
    delete: curl,
    triggers: [new Date().toString()],
  }, {
    hooks: {
      beforeCreate: [beforeHook],
      afterCreate: [afterHook],
      beforeUpdate: [beforeHook],
      afterUpdate: [afterHook],
      beforeDelete: [beforeHook],
      afterDelete: [afterHook],
    },
  })

  return {
    stdout: cmd.stdout,
  }
}

When we run pulumi up now, the hooks will be invoked before and after the relevant operation. Since our previous operation failed, we should expect to see a hooked create on our first run:

shell
pulumi up
Updating (...)

View in Browser (Ctrl+O): https://app.pulumi.com/...

     Type                      Name               Status              Info
 +   pulumi:pulumi:Stack       resource-hooks     created (3s)        3 messages
 +   └─ command:local:Command  curl               created (0.66s)

Diagnostics:
  pulumi:pulumi:Stack (resource-hooks):
    Opening tunnel
    Tunnel opened: 2131167
    Closing tunnel: 2131167

Outputs:
    stdout: "<!doctype html>\n<html>\n<head>\n    <title>Example Domain</title>\n\n    <meta charset=\"utf-8\" />\n    <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <style type=\"text/css\">\n    body {\n        background-color: #f0f0f2;\n        margin: 0;\n        padding: 0;\n        font-family: -apple-system, system-ui, BlinkMacSystemFont, \"Segoe UI\", \"Open Sans\", \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n        \n    }\n    div {\n        width: 600px;\n        margin: 5em auto;\n        padding: 2em;\n        background-color: #fdfdff;\n        border-radius: 0.5em;\n        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);\n    }\n    a:link, a:visited {\n        color: #38488f;\n        text-decoration: none;\n    }\n    @media (max-width: 700px) {\n        div {\n            margin: 0 auto;\n            width: auto;\n        }\n    }\n    </style>    \n</head>\n\n<body>\n<div>\n    <h1>Example Domain</h1>\n    <p>This domain is for use in illustrative examples in documents. You may use this\n    domain in literature without prior coordination or asking for permission.</p>\n    <p><a href=\"https://www.iana.org/domains/example\">More information...</a></p>\n</div>\n</body>\n</html>"

Resources:
    + 2 created

Duration: 5s

Success! The tunnel was opened before our create operation and our stack output contains the HTML of the page at example.com.

Another example: application health checks ​

Let's tackle a more realistic scenario where hooks can be useful. We'll take the how-to guide for creating an EC2 web server and add resource hooks to health check the web server before allowing Pulumi to mark the deployment as complete. In this way, we know that when Pulumi is finished, the application is up and ready to go!

typescript
import * as aws from "@pulumi/aws"
import * as pulumi from "@pulumi/pulumi"

export = async () => {
  // Define the instance's user data script to set up a simple HTTP server that
  // serves some static content. We'll try to fetch the health.json in a
  // lifecycle hook later on to check whether or not the server is up and running.
  const userData = `#!/bin/bash
echo "Hello, World!" > index.html
echo '{"ok": true}' > health.json
nohup python -m SimpleHTTPServer 80 &`

  // Define a resource hook that will run after create and update and not return
  // until the health check passes.
  const afterHook = new pulumi.ResourceHook("after", async args => {
    // Since this is an after hook, we'll have access to the new outputs of the
    // resource.
    const outputs = args.newOutputs as aws.ec2.InstanceState

    // Attempt to fetch health.json from the instance's public endpoint, backing
    // off linearly if it is not yet available.
    const maxRetries = 30
    for (let i = 0; i < maxRetries; i++) {
      try {
        const response = await fetch(`http://${outputs.publicDns}/health.json`)
        if (response.ok) {
          const data = await response.json()
          console.log(`Health check passed: ${JSON.stringify(data)}`)
          return
        }
      } catch (error) {
        console.log(`Health check attempt ${i + 1} failed`)
      }

      await new Promise(resolve => setTimeout(resolve, (i + 1) * 1000))
    }
  })

  // Set up the resources needed to run the web server, as outlined in the
  // how-to guide linked above.

  const instanceType = "t2.micro"
  const ami = aws.ec2.getAmiOutput({
    filters: [{
      name: "name",
      values: ["amzn2-ami-hvm-*"],
    }],
    // Amazon owns this AMI so we'll use their owner ID.
    owners: ["137112412989"],
    mostRecent: true,
  })

  const group = new aws.ec2.SecurityGroup("webserver-secgrp", {
    ingress: [
      { protocol: "tcp", fromPort: 22, toPort: 22, cidrBlocks: ["0.0.0.0/0"] },
      { protocol: "tcp", fromPort: 80, toPort: 80, cidrBlocks: ["0.0.0.0/0"] },
    ],
  })

  const server = new aws.ec2.Instance("webserver-www", {
    instanceType,
    vpcSecurityGroupIds: [group.id],
    ami: ami.id,
    userData,
  }, {
    hooks: {
      afterCreate: [afterHook],
      afterUpdate: [afterHook],
    },
  })

  return {
    publicDns: server.publicDns,
    publicIp: server.publicIp,
  }
}

Thanks to our hooks, pulumi up will now wait until the web server is up and running before marking the deployment as complete. We can see this in action thanks to our logging output:

shell
pulumi up
shell
Updating (...)

View in Browser (Ctrl+O): https://app.pulumi.com/...

     Type                      Name               Status            Info
 +   pulumi:pulumi:Stack       resource-hooks     created (79s)     6 messages
 +   ├─ aws:ec2:SecurityGroup  webserver-secgrp   created (3s)
 +   └─ aws:ec2:Instance       webserver-www      created (67s)

Diagnostics:
  pulumi:pulumi:Stack (resource-hooks):
    Health check attempt 1 failed
    Health check attempt 2 failed
    Health check attempt 3 failed
    Health check attempt 4 failed
    Health check attempt 5 failed
    Health check passed: {"ok":true}

Outputs:
    publicHostName: "ec2-XXX-YYY-ZZZ-WWW.us-west-2.compute.amazonaws.com"
    publicIp      : "XXX.YYY.ZZZ.WWW"

Resources:
    + 3 created

Duration: 1m21s

And indeed, a command such as curl http://ec2-XXX-YYY-ZZZ-WWW.us-west-2.compute.amazonaws.com/health.json returns {"ok":true} immediately, without us having to wait for the web server to start up after the pulumi up command completes!

Where can we go from here? ​

Resource hooks are a powerful new feature that allow you to run custom code at any point in the resource lifecycle. This opens up a wide range of possibilities, such as:

  • Custom application health checks after creating or updating resources
  • Collecting logs or metrics when your Pulumi resources change
  • Running custom scripts such as database migrations as part of your Pulumi workflow.

INFO

Resource hooks require Pulumi to run your program. For refresh and destroy operations, this means you must use the --run-program flag for hooks to work. Read the full documentation on resource hooks to learn more.

Share any issues with your experience with us on GitHub, X, or our Community Slack.

Content from the official Pulumi documentation (github.com/pulumi/docs).