Skip to content

Resource option: hooks ​

The hooks resource option provides a set of resource hooks linked to a resource. Hooks are used to execute custom logic at specific points in the resource lifecycle, such as before or after creation, update, or deletion.

INFO

Resource hooks are supported in TypeScript/JavaScript, Python, Go, and C#/.NET. Java and YAML do not support resource hooks.

Each hook is a callback that the Pulumi engine invokes. Hooks that execute before an action are called before hooks and have names beginning with before or Before depending on the language. Hooks that execute after an action are called after hooks and have names beginning with after or After depending on the language. Pulumi supports the following hook types:

  • Create hooks are called before or after a resource is created. This may occur during the initial creation of a resource or when a resource requires replacement, for example because of a change to an immutable property.

  • Update hooks are called before or after a resource is updated in-place.

  • Delete hooks are called before or after a resource is deleted. This may occur during the deletion of a resource due to a destroy or that resource's removal from the program, or as part of a resource replacement, for example because of a change to an immutable property.

Alongside these before and after hooks, error hooks run when a resource operation fails and can ask the engine to retry it.

When a hook is executed as part of a resource operation, it receives the resource's URN and ID, as well as any relevant input and output properties. Hooks may return errors. If a before hook returns an error, the action it precedes is not executed and the Pulumi operation fails with that error. If an after hook returns an error, the underlying resource operation has already completed and is recorded in the state, but the deployment then fails. To opt out of this behavior and instead log a warning and continue, set the ignoreErrors option on the hook. The table below illustrates the combinations of inputs, outputs, and error behaviors for each hook type:

Hook typeOld inputsNew inputsOld outputsNew outputsError behavior
Before create✓Prevent creation, fail deployment
After create✓✓Record resource in state, then fail deployment
Before update✓✓✓Prevent update, fail deployment
After update✓✓✓✓Record update in state, then fail deployment
Before delete✓✓Prevent deletion, fail deployment
After delete✓✓Record deletion in state, then fail deployment

INFO

Before Pulumi v3.238.0, after hooks that returned an error logged a warning and the deployment continued. Starting with v3.238.0, an after-hook failure fails the deployment by default. Use the ignoreErrors hook option to restore the previous behavior, or pass --continue-on-error to pulumi up/pulumi destroy to keep processing other resources after a hook failure.

Health checking example ​

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 python3 -m http.server 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.

  const instanceType = "t2.micro"
  const ami = aws.ec2.getAmiOutput({
    filters: [{
      name: "name",
      values: ["al2023-ami-2023.*-x86_64"],
    }],
    // 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,
  }
}

Ignoring hook errors ​

By default, when any hook (before or after) returns an error, the Pulumi deployment fails. For after hooks, the underlying resource operation has already succeeded by the time the hook runs, so its result is recorded in the state before the deployment fails.

If a hook failure should not be treated as fatal — for example, a best-effort notification or audit step — set the ignoreErrors option when constructing the hook. Errors from that hook are logged as warnings and the deployment continues.

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

const notifyHook = new pulumi.ResourceHook("notify", async args => {
    // Best-effort notification. Failures here should not fail the deployment.
    await sendNotification(args);
}, {
    ignoreErrors: true,
});

To keep applying other resources after a hook failure on a single update, you can also run pulumi up (or pulumi destroy) with the --continue-on-error flag. This applies to the whole deployment, not only to hooks.

Deletions and delete hooks ​

For delete hooks to run successfully, Pulumi must have access to any necessary hooks at the time of the deletion. The two bullets below are alternatives, not sequential steps — follow the one that matches how you are deleting the resources:

  • Deleting some resources with pulumi up. When removing resources from your program, first remove only the resources you wish to delete, leaving any delete hooks in place. On the next pulumi up, Pulumi deletes the resources and runs any relevant delete hooks. Once this operation is complete, you can then remove the delete hooks from your program.

  • Deleting a whole stack with pulumi destroy. You must pass the --run-program flag to instruct Pulumi to run your program and register any hooks that are to be executed. If Pulumi detects that you are trying to destroy a stack that contains hooks without the --run-program flag, it fails with an error. See Running your program on refresh and destroy for other situations where the flag is useful.

Error hooks ​

Like the other resource hooks, which run before and after certain operations, you can also add hooks to run when operations fail. For example, you can use an error hook to retry a failing resource registration, or to change the error-handling behavior based on the error encountered. The inputs and outputs an error hook receives depend on the operation that fails:

Failed operationOld inputsNew inputsOld outputs
create✓
update✓✓✓
delete✓✓

As well as the standard hook information and the name of the failing operation, error hooks also receive a list of errors encountered during previous runs (starting with the most recent). In other words, if a resource has failed three times, the hook receives three errors. The hook must then reply with a flag that determines whether to retry the operation, or whether to let the failure cascade and exit the program. Retries are capped: an operation can be retried at most 100 times, after which the deployment fails as normal.

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

const notStartedRetryHook = new pulumi.ErrorHook(
    "retry-when-not-started",
    async (args) => {
        const latestError = args.errors[0] ?? "";

        if (!latestError.includes("resource has not yet started")) {
          return false; // do not retry, this is another type of error
        }

        await new Promise((resolve) => setTimeout(resolve, 5000));
        return true; // retry
    },
);

const res = new MyResource("res", {}, {
    hooks: {
        onError: [notStartedRetryHook],
    },
});

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