Skip to content

Write a policy pack ​

If Pulumi's pre-built policy packs don't meet your requirements, you can write custom policy packs. Custom policies let you enforce any compliance, security, or operational rule.

Policies can be written in TypeScript/JavaScript (Node.js), Python, or OPA (Rego) and can be applied to Pulumi stacks written in any language. Learn more about language support for policies.

Creating a Policy Pack with Neo ​

This guide walks you through creating a policy pack manually, but Neo can help streamline the process.

Neo can generate policy pack content tailored to your preferred programming language and cloud providers, allowing you to quickly build policies that meet your specific requirements while reducing errors. When paired with the GitHub App, Neo can even open pull requests directly in your repository.

Here are some example prompts to inspire your workflow:

"Create a boilerplate TypeScript policy pack at <GitHub Repository>"
"Create a policy to enforce encryption of S3 buckets"
"Create a policy that requires environment tagging on all Google Cloud resources"

Prerequisites ​

Before authoring your first policy pack, ensure you have:

  • Pulumi CLI installed.
  • For TypeScript/JavaScript policies: Node.js installed.
  • For Python policies: Python installed.
  • For OPA policies: the OPA language plugin, installed with pulumi plugin install language opa.
  • (Optional) Access to Pulumi Cloud if you want to publish and centrally manage policy packs. Not required for local policy pack usage with open source Pulumi.
  • An understanding of Policy as Code core concepts.

The runtime you choose here also becomes a requirement for everyone who runs Pulumi against a stack your pack governs. See runtime requirements.

Creating a policy pack ​

Create your first policy pack:

  1. Create a directory for your policy pack and navigate to it.

    sh
    $ mkdir policypack && cd policypack
  2. Create a new TypeScript project:

    sh
    $ pulumi policy new aws-typescript
  3. Replace the generated policy in index.ts with this example, which demonstrates a clearer pattern for organizational policy enforcement:

    Each policy must have:

    • A unique name, description, and validation function
    • A validation function (this example uses validateResourceOfType to run only for AWS RDS instance resources)
    • An enforcement level set at the policy pack level (applies to all policies) or per policy (overrides the pack level)

    For more information on all available fields, see policy fields.

    typescript
    import * as aws from "@pulumi/aws";
    import { PolicyPack, validateResourceOfType } from "@pulumi/policy";
    
    // Create a new policy pack.
    new PolicyPack("policy-pack-typescript", {
        // Specify the policies in the policy pack.
        policies: [{
            // The name for the policy must be unique within the pack.
            name: "rds-storage-encryption",
    
            // The description should document what the policy does and why it exists.
            description: "Requires RDS instances to have storage encryption enabled, unless tagged as non-production data.",
    
            // The enforcement level can be "advisory", "mandatory", "remediate", or "disabled". An "advisory"
            // enforcement level simply prints a warning for users, a "mandatory" policy will block an update
            // from proceeding, "remediate" fixes the violation automatically, and "disabled" disables the
            // policy from running.
            enforcementLevel: "mandatory",
    
            // The validateResourceOfType function allows you to filter resources. In this case, the rule only
            // applies to RDS instances and reports a violation when storage encryption is not enabled.
            validateResource: validateResourceOfType(aws.rds.Instance, (instance, args, reportViolation) => {
                // Exempt instances explicitly tagged as non-production data.
                if (instance.tags?.["data-classification"] === "non-production") {
                    return;
                }
                if (!instance.storageEncrypted) {
                    reportViolation(
                        "RDS instance must have storage encryption enabled " +
                        "(or be tagged 'data-classification=non-production').");
                }
            }),
        }],
    });

You can find more example policy packs in the Pulumi examples repository.

Testing your policies ​

Write unit tests to verify your policies work correctly before publishing.

Here's a simple test example using Mocha and assert:

typescript
describe("rds-storage-encryption-policy", () => {
    it("should pass when storage encryption is enabled", () => {
        const args = getEmptyArgs();
        args.type = "aws:rds/instance:Instance";
        args.props.storageEncrypted = true;
        assert.doesNotThrow(() => {
            runResourcePolicy(rdsStorageEncryptionPolicy, args);
        });
    });

For a complete example including test helpers and setup, see the unit test policy example on GitHub.

Resource validation vs stack validation ​

Pulumi policies validate at two scopes:

Resource validation policies ​

Resource validation policies run during pulumi preview or pulumi up, examining each resource before creation or update. These policies execute before the engine sends the resource to the provider, which means they can block non-compliant resources during both preview and update operations.

Use resource validation policies when you need to:

  • Enforce rules on specific resource types (e.g., "S3 buckets must have encryption enabled")
  • Validate resource properties before deployment
  • Block individual non-compliant resources

Stack validation policies ​

Stack validation policies run once, at the end of the pass, against the finished resource graph, on both pulumi preview and pulumi up. Unlike resource validation, which checks each resource as it is registered, stack validation waits until every resource in the update has been processed so it can examine relationships between them and enforce stack-wide rules. A property that stays unknown until the change is actually applied is still unknown when a stack policy inspects it during preview.

Use stack validation policies when you need to:

  • Validate relationships between resources (e.g., "databases must be in private subnets")
  • Enforce stack-wide rules (e.g., "stack must not exceed 50 resources")
  • Examine the complete resource graph

Most policies are resource validation policies. Stack validation policies are useful for more complex scenarios that require understanding the full context of your infrastructure.

The following example limits the number of S3 buckets in a stack:

In TypeScript, use the validateStack callback to access all resources in the stack:

typescript
import { PolicyPack } from "@pulumi/policy";

new PolicyPack("stack-policies", {
    policies: [{
        name: "maximum-s3-bucket-count",
        description: "Limits the number of S3 buckets per stack.",
        enforcementLevel: "mandatory",
        validateStack: (args, reportViolation) => {
            const buckets = args.resources.filter(
                r => r.type === "aws:s3/bucket:Bucket"
            );
            if (buckets.length > 3) {
                reportViolation(
                    `Stack has ${buckets.length} S3 buckets, maximum allowed is 3.`);
            }
        },
    }],
});

Using stack tags in policies ​

Stack validation policies can access tags assigned to the stack via args.stackTags (TypeScript) or args.stack_tags (Python). This lets you enforce tagging standards, like requiring every stack to declare an environment or owning team, as a governance gate.

The following example requires env and team tags on every stack. Because args.stackTags only contains tags that existed before the current update, the policy also checks for StackTag resources in the stack so it passes on the first deployment when tags are created declaratively.

typescript
import { PolicyPack } from "@pulumi/policy";

const requiredTags = ["env", "team"];

new PolicyPack("stack-tag-policies", {
    policies: [{
        name: "require-stack-tags",
        description: "Requires 'env' and 'team' tags on every stack.",
        enforcementLevel: "mandatory",
        validateStack: (args, reportViolation) => {
            // Collect tag names set via StackTag resources in this deployment.
            const resourceTagNames = args.resources
                .filter(r => r.type === "pulumiservice:index:StackTag")
                .map(r => r.props.name as string);

            for (const tag of requiredTags) {
                const inStackTags = args.stackTags.has(tag);
                const inResources = resourceTagNames.includes(tag);
                if (!inStackTags && !inResources) {
                    reportViolation(`Missing required stack tag: '${tag}'.`);
                }
            }
        },
    }],
});

INFO

Stack tags are available on both StackValidationArgs and ResourceValidationArgs, so resource-level policies can also make decisions based on stack metadata.

You can assign tags to a stack using the CLI (pulumi stack tag set), the pulumi:tags config in your Pulumi.yaml or Pulumi.<stack>.yaml file, the StackTag resource from the Pulumi Cloud provider, the Pulumi Cloud console, or the Stack Tags REST API. To learn how to apply policy packs to groups of stacks, see policy groups.

INFO

Stack tags are not currently accessible in OPA policies. OPA stack-level policies can validate the full set of resources using input.resources (see Creating a policy pack for rule prefix conventions), but they cannot read stack tag metadata. Use TypeScript or Python policies if you need to enforce stack tag requirements.

Remediating policy violations ​

A remediate enforcement level goes a step further than mandatory: instead of only reporting a violation, the policy inspects the resource's properties, fixes the problem, and returns the corrected properties. The engine substitutes the remediated state for the state the Pulumi program originally produced, so the deployment proceeds with compliant resources rather than being blocked or merely flagged.

Remediation is only available to resource validation policies. Stack validation policies examine relationships across the whole resource graph after registration completes, by which point there is no single resource left to substitute a fix into, so a stack policy set to remediate is treated as mandatory instead.

The following example remediates, rather than validates, the RDS storage encryption policy shown earlier: instead of blocking an unencrypted instance, it turns on encryption automatically.

Use remediateResource, built with the remediateResourceOfType helper, in place of validateResource:

typescript
import * as aws from "@pulumi/aws";
import { PolicyPack, remediateResourceOfType } from "@pulumi/policy";

new PolicyPack("policy-pack-typescript", {
    policies: [{
        name: "rds-storage-encryption",
        description: "Requires RDS instances to have storage encryption enabled, unless tagged as non-production data.",
        enforcementLevel: "remediate",
        remediateResource: remediateResourceOfType(aws.rds.Instance, (instance, args) => {
            // Exempt instances explicitly tagged as non-production data.
            if (instance.tags?.["data-classification"] === "non-production") {
                return;
            }
            if (!instance.storageEncrypted) {
                instance.storageEncrypted = true;
                return instance;
            }
            return undefined;
        }),
    }],
});

If a policy needs to both validate and remediate, validateRemediateResourceOfType builds a matched pair of validateResource and remediateResource callbacks from a single validation function.

A few behaviors are specific to remediation:

  • If a resource still triggers a violation after remediation runs, the reported level is downgraded from remediate to mandatory, and the deployment is blocked rather than silently allowed through with an unresolved problem.
  • When more than one policy pack applies to a resource, their remediations run sequentially in the order the packs were loaded, and each remediation sees the resource state as modified by the ones that ran before it, so a later remediation can build on an earlier one.
  • A policy whose enforcement level is remediate but which does not implement a remediation function is treated as mandatory, so its violations block the deployment.
  • The remediationSteps metadata field (see policy fields) is unrelated to automatic remediation: the field is manual guidance shown to a user for policies that only validate, describing how to fix a violation by hand.

Writing policies for dynamic providers ​

Dynamic providers allow you to create custom resource types directly in your Pulumi programs. When writing policies for dynamic providers, you need to account for a key constraint: by default, all dynamic resources share the same resource type (pulumi-nodejs:dynamic:Resource for TypeScript/JavaScript or pulumi-python:dynamic:Resource for Python).

Since you cannot rely on the resource type alone to identify which dynamic provider a resource uses, you must inspect the resource's properties to differentiate between different dynamic provider implementations.

Example: Validating a specific dynamic provider ​

This example shows how to write a policy that validates resources from a specific dynamic provider by checking for a unique property:

typescript
import * as pulumi from "@pulumi/pulumi";
import { PolicyPack, ResourceValidationPolicy } from "@pulumi/policy";

new PolicyPack("dynamic-provider-policies", {
    policies: [{
        name: "environment-name-validation",
        description: "Validates that environment dynamic resources use the correct name.",
        enforcementLevel: "mandatory",
        validateResource: (args, reportViolation) => {
            // All dynamic resources in TypeScript/JavaScript have the type "pulumi-nodejs:dynamic:Resource".
            // To identify a specific dynamic provider, check for unique properties.
            if (args.type === "pulumi-nodejs:dynamic:Resource" && args.props.environmentName !== undefined) {
                const envName = args.props.environmentName;
                if (envName !== "myTestEnv") {
                    reportViolation(
                        `Environment name must be 'myTestEnv'. Current value: '${envName}'`);
                }
            }
        },
    }],
});

Best practices for dynamic provider policies ​

When writing policies for dynamic providers:

  1. Identify unique properties: Determine which properties uniquely identify the dynamic provider you want to validate. In the example above, the environment_name (or environmentName) property indicates this is an environment resource.

  2. Be specific with property checks: Since all dynamic resources share the same type, check for specific property names or combinations that distinguish your dynamic provider from others.

  3. Handle missing properties gracefully: Use property existence checks (like "environment_name" in args.props) before accessing property values to avoid errors when the policy runs against other dynamic providers.

  4. Document your assumptions: Clearly document which properties your policy uses to identify dynamic providers so that changes to the dynamic provider implementation don't inadvertently break policy enforcement.

Inspecting resource options ​

Resource validation callbacks receive an args.opts object of type PolicyResourceOptions. It mirrors the resource options set on the resource under validation, letting policies make decisions based on how a resource is configured rather than only its properties. The available fields are:

  • protect — whether the resource is protected from deletion.
  • ignoreChanges (ignore_changes in Python) — properties whose changes the engine ignores.
  • deleteBeforeReplace (delete_before_replace) — whether the resource is deleted before its replacement is created.
  • aliases — additional URNs aliased to the resource.
  • customTimeouts (custom_timeouts) — custom create, update, and delete timeouts.
  • additionalSecretOutputs (additional_secret_outputs) — outputs always treated as secrets.
  • parent — the URN of the resource's parent. For a resource created directly at the stack root rather than as a child of another resource or component, this is the URN of the root stack resource (type pulumi:pulumi:Stack).

Example: Enforcing a resource's parent ​

The parent option is useful for enforcing that certain resources are only created as children of the component that is supposed to manage them, rather than loose at the stack root or under the wrong parent. Because parent is the parent's URN, you can extract the parent's type token from it: a URN has the form urn:pulumi:{stack}::{project}::{parentType}${resourceType}::{name}, so the type is the third ::-delimited segment, and the resource's own type is the token after the last $.

The following example requires that every aws:rds/instance:Instance is a child of a my:components:Database component:

typescript
import * as aws from "@pulumi/aws";
import { PolicyPack, validateResourceOfType } from "@pulumi/policy";

const requiredParentType = "my:components:Database";

new PolicyPack("parent-policies", {
    policies: [{
        name: "rds-instance-parent",
        description: "Requires RDS instances to be managed by a Database component.",
        enforcementLevel: "mandatory",
        validateResource: validateResourceOfType(aws.rds.Instance, (instance, args, reportViolation) => {
            // args.opts.parent is the parent's URN; for a resource at the stack root it is the root stack's URN (type pulumi:pulumi:Stack).
            const parentUrn = args.opts.parent;
            const parentType = parentUrn?.split("::")[2]?.split("$").pop();
            if (parentType !== requiredParentType) {
                reportViolation(
                    `RDS instances must be a child of a '${requiredParentType}' component.`);
            }
        }),
    }],
});

INFO

args.opts is available on ResourceValidationArgs (resource validation policies), not on StackValidationArgs. To reason about parent-child relationships across the full resource graph, use a stack validation policy and inspect args.resources. See resource options for what each option means on the resource side.

Running policies locally ​

Test your policy pack locally before publishing.

  1. Use the --policy-pack flag to specify your policy pack directory:

    If you need a test program, create one with pulumi new aws-typescript and replace the generated code with a compliant (encrypted) RDS instance:

    typescript
    import * as aws from "@pulumi/aws";
    
    const db = new aws.rds.Instance("my-db", {
        engine: "postgres",
        instanceClass: "db.t3.micro",
        allocatedStorage: 20,
        username: "admin",
        manageMasterUserPassword: true,
        skipFinalSnapshot: true,
        storageEncrypted: true,
    });

    For AWS examples, ensure you have AWS credentials configured and set your region with pulumi config set aws:region <region>.

  2. In the Pulumi program's directory, run:

    sh
    $ pulumi preview --policy-pack <path-to-policy-pack-directory>

    If the stack is compliant, the output shows which policy packs ran.

    output
    Previewing update (dev):
            Type                  Name          Plan
        +   pulumi:pulumi:Stack   test-dev      create
        +   └─ aws:rds:Instance   my-db         create
    
    Resources:
        + 2 to create
    
    Policy Packs run:
        Name                                                 Version
        aws-typescript (/Users/user/path/to/policy-pack)     (local)
  3. Edit the stack code to disable storage encryption:

    typescript
    storageEncrypted: false,
  4. Run pulumi preview again. This time, the policy violation blocks the preview:

    output
    Previewing update (dev):
            Type                  Name          Plan       Info
        +   pulumi:pulumi:Stack   test-dev      create     1 error
        +   └─ aws:rds:Instance   my-db         create
    
    Policies:
        ❌ policy-pack-typescript@v0.0.1 (local: <path-to-policy-pack>)
            - [mandatory]  rds-storage-encryption  (aws:rds:Instance: my-db)
              RDS instance must have storage encryption enabled (or be tagged 'data-classification=non-production').
    
    Diagnostics:
        pulumi:pulumi:Stack (test-dev):
        error: preview failed

Configuring policy packs ​

Configuration makes policy packs flexible and reusable. Adjust enforcement levels, allowed values, and other settings without modifying code.

Enforcement levels ​

All policies support configurable enforcement levels. Set enforcement for all policies in a pack or override individual policies:

json
{
    "all": {
        "enforcementLevel": "advisory"
    },
    "critical-security-policy": {
         "enforcementLevel": "mandatory"
    }
}

As shorthand, specify enforcement levels directly:

json
{
    "all": "advisory",
    "critical-security-policy": "mandatory"
}

Enforcement levels:

In Pulumi Cloud, Essentials reports organization-managed policies in advisory mode, and Pro adds mandatory enforcement.

  • advisory - Issues warnings but allows deployments to proceed
  • mandatory - Blocks deployments when violations are detected
  • remediate - Automatically fixes violations in place, available in the Enterprise edition; see Remediating policy violations
  • disabled - Skips policy evaluation entirely

Custom configuration ​

Policy authors define configuration schemas using JSON Schema, enabling administrators to customize policy behavior without code changes.

Example: Optional configuration with defaults

typescript
const examplePolicy: ResourceValidationPolicy = {
    name: "example-policy-with-schema",
    description: "Example policy with configurable message.",
    configSchema: {
        properties: {
            message: {
                type: "string",
                minLength: 5,
                maxLength: 50,
            }
        },
    },
    validateResource: validateResourceOfType(aws.rds.Instance, (_, args, reportViolation) => {
        const config = args.getConfig<{ message?: string }>();
        const message = config.message || "Using default message";
        reportViolation("Configured message: " + message);
    }),
}

Example: Required configuration

To require configuration values, add them to the required list:

typescript
configSchema: {
    properties: {
        message: {
            type: "string",
            minLength: 5,
            maxLength: 50,
        }
    },
    required: ["message"],
}

Using configuration files ​

Local execution ​

Pass configuration via JSON file:

config.json:

json
{
    "all": "mandatory",
    "example-policy-with-schema": {
        "message": "Resources must follow naming standards"
    }
}

Run with configuration:

bash
pulumi preview --policy-pack <path-to-policy-pack> --policy-pack-config config.json

To exempt specific violations, use version 2 of the file format, which nests the configuration under policies and adds exceptions:

json
{
    "version": 2,
    "policies": {
        "all": "mandatory"
    },
    "exceptions": {
        "log-buckets": {
            "reason": "Log target buckets must allow the log delivery group",
            "match": [
                {
                    "policies": ["s3-no-public-read"],
                    "targets": ["urn:pulumi:prod::web::aws:s3/bucket:Bucket::logs"]
                }
            ]
        }
    }
}

For the format and how exceptions apply, see Policy exceptions.

Pulumi Cloud configuration ​

After publishing, administrators configure policy packs through the Pulumi Cloud console or CLI.

Using the console:

  1. Navigate to your Policy Group
  2. Click Add Policy Pack
  3. Select the policy pack
  4. Fill in the configuration form (automatically validated against the schema)
  5. Save the configuration

Using the CLI:

Validate configuration before enabling:

bash
pulumi policy validate-config <org>/<pack-name> <version> --config config.json

Enable with configuration:

bash
pulumi policy enable <org>/<pack-name> <version> --config config.json

Or for a specific policy group:

bash
pulumi policy enable <org>/<pack-name> <version> --config config.json --policy-group <group-name>

Using ESC environments ​

Policy packs can also receive configuration and secrets from Pulumi ESC environments. When you attach an ESC environment to a policy pack in a policy group, values defined under the policyConfig reserved property are available to your policies at runtime. You can also use environmentVariables to inject environment variables into the policy runtime.

Publishing to your organization ​

After local validation, publish your policy pack to Pulumi Cloud. Policy enforcement runs automatically during preview and update for every stack in a preventative policy group that includes the pack.

Pulumi Cloud versions policy packs, enabling updates, rollbacks, and gradual rollouts.

  1. From the policy pack directory, publish:

    sh
    $ pulumi policy publish <org-name>

    Pulumi Cloud publishes the pack under the version you set:

    Obtaining policy metadata from policy plugin
    Compressing policy pack
    Uploading policy pack to Pulumi Cloud
    Publishing my-policy-pack to myorg
    Published as version 1.0.0

Managing policy pack versions ​

Policy pack versions are managed differently by language:

  • TypeScript/JavaScript: Set the version field in package.json. You can also set version in PulumiPolicy.yaml to override it.
  • Python: Set the version field in PulumiPolicy.yaml
  • OPA: Set the version field in PulumiPolicy.yaml

For a complete list of PulumiPolicy.yaml fields, see the project file reference.

Each version can only be published once.

Publishing a new version:

  1. Update the version number:

    • TypeScript: Edit package.json: "version": "0.0.2"
    • Python: Edit PulumiPolicy.yaml: version: 0.0.2
    • OPA: Edit PulumiPolicy.yaml: version: 0.0.2
  2. Publish:

    bash
    pulumi policy publish <org-name>

If you try to republish an existing version, you'll see:

error: [400] Bad Request: Policy Pack "aws-typescript" (Version 0.0.1) has already been published.
Please specify a new version tag.

We recommend semantic versioning:

  • Major (1.0.0 → 2.0.0): Breaking changes to policy behavior
  • Minor (1.0.0 → 1.1.0): New policies added
  • Patch (1.0.0 → 1.0.1): Bug fixes

After publishing, your policy pack appears in Pulumi Cloud's policy pack list. Apply it to stacks or cloud accounts using policy groups. See Get Started with Pulumi Policies for details.

Considerations for authoring policies ​

Best practices for authoring policy packs:

Naming policies ​

Each policy within a policy pack must have a unique name. The name must be between 1 and 100 characters and may contain letters, numbers, dashes (-), underscores (_), or periods (.).

Policy assertions ​

Write policy assertions as complete sentences in imperative tone, specifying which resource violated the policy.

✅ Good❌ Poor
"The RDS cluster must specify a node type.""Specify a node type."
"The RDS cluster must have audit logging enabled.""Enable audit logging."
"S3 bucket must use 'mycompany-' prefix.""Use correct prefix."

This format helps users understand which resource failed and why.

Examples and resources ​

Next steps ​

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