Skip to content

Build a Component ​

This guide will walk you through the steps of making a Pulumi Component suitable for reuse in all languages and cloud environments.

INFO

Prerequisites:

Why Write a Component? ​

Components encapsulate best practices, propagate resource options to every resource they create, appear as a single node in your stack, and can be shared across teams and languages.

For the full case — including when a plain function is the better choice — see When to Build a Component.

How It Works ​

Pulumi Components are implemented as custom classes in any Pulumi-supported language. A component extends pulumi.ComponentResource and groups multiple resources into a single, reusable abstraction, letting you define infrastructure once and apply it consistently across multiple environments.

Once you've written a component, you have a few options for how to share it:

  • Use it directly in a Pulumi program written in the same language as the component — the simplest path when the component will only ever be used from that one language.
  • Publish it as a native-language package (npm, PyPI, NuGet, Maven, Go modules) so other Pulumi programs in the same language can install it like any other library.
  • Package it as a Pulumi plugin package so it can be consumed from any Pulumi-supported language via a generated SDK. This is the recommended path for components meant for broad reuse — see Authoring a Source-Based Plugin Package.

Structure of a Component ​

A Pulumi Component consists of two main parts you write:

  • The component resource encapsulates multiple Pulumi resources, grouping them into a logical unit.
  • The component resource arguments define configurable input properties, allowing users to specify parameters that tailor the component's behavior to specific needs.

This guide focuses on writing those two parts. To turn the component into an installable plugin package — adding PulumiPlugin.yaml, the language manifest, and the entry file that hosts the provider — see Authoring a Source-Based Plugin Package once you've written your class.

Example: Static Web Page Component ​

In this example, we'll create a static website component in AWS Simple Storage Service (S3). The component will manage the following five child resources necessary to implement a basic S3 hosted static website:

The component will take as input the contents of the file you wish to host, and will output the S3 endpoint used to access it.

Example: Using the custom StaticPage component in a Pulumi Program

yaml
name: sample-components-yaml
description: A Pulumi YAML program that builds and uses a static page component
runtime:
  name: yaml
packages:
  sample-components: ./sample-components
resources:
  my-static-page:
    type: sample-components:StaticPage
    properties:
      indexContent: "<h1>I love Pulumi!</h1>"
outputs:
  websiteURL: http://${my-static-page.endpoint}

The core implementation of the AWS API is handled by the Pulumi AWS Provider, which gives us those five underlying resource types. Our StaticPage component will work with those existing resource types and create a new type of resource with a simpler API.

The walkthrough below focuses on the component class itself. The surrounding project layout — the directory, PulumiPlugin.yaml, language manifest (package.json, pyproject.toml, go.mod, .csproj, or pom.xml), and entry file — is covered in Authoring a Source-Based Plugin Package. You can scaffold the project there first and return here for the class implementation, or write the class first and wrap it later.

Implement the Component ​

Next we will define the classes that implement our reusable component.

Components typically require two parts: a subclass of pulumi.ComponentResource that implements the component, and an arguments class, which is used to configure the component during construction.

Add the required imports ​

First create a file called StaticPage.ts, and add the imports we will need:

Example: StaticPage.ts required imports

ts
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

The @pulumi/pulumi package is the core Pulumi SDK, which provides the base classes and types needed to define components and resources. The @pulumi/aws package is the Pulumi AWS provider, which gives us the resource types we need to create AWS infrastructure.

Define the Component arguments ​

Next, we will declare the component's arguments. Most languages model these as a class; Go uses a struct, and YAML uses an inputs: block. In our example, we'll pass the contents of the webpage we want to host into the component.

Example: StaticPage.ts the Component arguments implementation

ts
export interface StaticPageArgs {
    indexContent: pulumi.Input<string>;
}

Note that argument classes must be serializable and use pulumi.Input types, rather than the language's default types. Certain types like union types (e.g., string | number) and functions are not supported due to schema inference limitations. For details on type requirements and limitations, see Component arguments and type requirements.

Define the Component resource ​

Now we can implement the component itself. Components should inherit from pulumi.ComponentResource, and should accept the arguments class we just defined in the constructor. All the work for our component happens in the constructor, and outputs are returned via class properties. At the end of the process, calling self.registerOutputs signals Pulumi that the process of creating the component resource has completed.

Example: StaticPage.ts the Component implementation

ts
export class StaticPage extends pulumi.ComponentResource {
    public readonly endpoint: pulumi.Output<string>;

    constructor(name: string, args: StaticPageArgs, opts?: pulumi.ComponentResourceOptions) {
        super("sample-components:index:StaticPage", name, args, opts);

        const bucket = new aws.s3.Bucket(`${name}-bucket`, {}, { parent: this });

        const bucketWebsite = new aws.s3.BucketWebsiteConfiguration(
            `${name}-website`,
            {
                bucket: bucket.bucket,
                indexDocument: { suffix: "index.html" },
            },
            {
                parent: this,
            },
        );

        new aws.s3.BucketObject(
            `${name}-index-object`,
            {
                bucket: bucket.bucket,
                key: "index.html",
                content: args.indexContent,
                contentType: "text/html",
            },
            {
                parent: this,
            },
        );

        const publicAccessBlock = new aws.s3.BucketPublicAccessBlock(
            `${name}-public-access-block`,
            {
                bucket: bucket.id,
                blockPublicAcls: false,
            },
            {
                parent: this,
            },
        );

        new aws.s3.BucketPolicy(
            `${name}-bucket-policy`,
            {
                bucket: bucket.id,
                policy: bucket.bucket.apply(this.allowGetObjectPolicy),
            },
            {
                parent: this,
                dependsOn: publicAccessBlock,
            },
        );

        this.endpoint = bucketWebsite.websiteEndpoint;

        this.registerOutputs({
            endpoint: bucketWebsite.websiteEndpoint,
        });
    }

    allowGetObjectPolicy(bucketName: string) {
        return JSON.stringify({
            Version: "2012-10-17",
            Statement: [
                {
                    Effect: "Allow",
                    Principal: "*",
                    Action: ["s3:GetObject"],
                    Resource: [`arn:aws:s3:::${bucketName}/*`],
                },
            ],
        });
    }
}

Detailed implementation breakdown ​

Let's dissect this component implementation piece-by-piece:

Inheriting from the base class ​

ts
export class StaticPage extends pulumi.ComponentResource {

Inheriting from pulumi.ComponentResource gives us some built-in behind-the-scenes behavior that allows the component state to be tracked and run within the Pulumi engine and within its host provider. It also allows the underlying library to find and infer the schema of the component.

Outputs as class properties ​

ts
    public readonly endpoint: pulumi.Output<string>;

We use a class property to store the output value. Component outputs should always use pulumi.Output<T> rather than plain types. This ensures that outputs can be passed directly to other Pulumi resource inputs, which also accept pulumi.Output<T>, without any additional unwrapping or conversion.

The Component constructor ​

ts
    constructor(name: string, args: StaticPageArgs, opts?: pulumi.ComponentResourceOptions) {
        super("sample-components:index:StaticPage", name, args, opts);

The constructor has a few standard arguments:

  • name: The name given to an instance of this component. When writing a Pulumi program, resources are named by the end-user. Later on in the implementation we will use this base component name to uniquely name the resources it contains.
  • args: This is an instance of the argument class we defined earlier, containing the inputs for our component.
  • opts: This is an optional set of common resource configuration values. The ComponentResourceOptions class is part of the basic API for all Pulumi resources, and will be passed to the constructors of our child resources later on.

The constructor calls the base class constructor, super(...). Its first parameter is the resource type name, in the format <package-name>:<module>:<component-class-name>, where the module is usually index. If you change the type name later, Pulumi deletes and recreates existing component instances unless you add an alias for the old name. The constructor also passes its name, args, and opts values to super(...).

WARNING

Changing the resource type name after a component has been deployed will cause all existing resources of that type to be recreated. Change the type name with extreme caution.

Child resources ​

All five child resources — Bucket, BucketWebsiteConfiguration, BucketObject, BucketPublicAccessBlock, and BucketPolicy — are created inside the constructor:

ts
        const bucket = new aws.s3.Bucket(`${name}-bucket`, {}, { parent: this });

        const bucketWebsite = new aws.s3.BucketWebsiteConfiguration(
            `${name}-website`,
            {
                bucket: bucket.bucket,
                indexDocument: { suffix: "index.html" },
            },
            {
                parent: this,
            },
        );

        new aws.s3.BucketObject(
            `${name}-index-object`,
            {
                bucket: bucket.bucket,
                key: "index.html",
                content: args.indexContent,
                contentType: "text/html",
            },
            {
                parent: this,
            },
        );

        const publicAccessBlock = new aws.s3.BucketPublicAccessBlock(
            `${name}-public-access-block`,
            {
                bucket: bucket.id,
                blockPublicAcls: false,
            },
            {
                parent: this,
            },
        );

        new aws.s3.BucketPolicy(
            `${name}-bucket-policy`,
            {
                bucket: bucket.id,
                policy: bucket.bucket.apply(this.allowGetObjectPolicy),
            },
            {
                parent: this,
                dependsOn: publicAccessBlock,
            },
        );

When creating child resources inside the component:

  • Set parent: this on every child resource so it appears under the component in the resource graph and inherits the component's provider configuration.
  • Template each child resource's name with the component's name parameter (e.g., `${name}-bucket`).

WARNING

Always template child resource names with the component's name parameter. If you hard-code a name like "bucket", every instance of the component will try to register a resource with the same name and Pulumi will fail with a duplicate-URN error. Renaming a component instance also won't propagate to its hard-coded children, which can cause replacement conflicts on the next update.

Handling outputs ​

The last part of the constructor handles output values. First we set the endpoint class property to the website endpoint from the BucketWebsiteConfiguration class. Note that this is a pulumi.Output<string>, not a regular TypeScript string. Outputs must use pulumi.Output types.

Finally, calling this.registerOutputs signals Pulumi that the component creation process has completed.

ts
        this.endpoint = bucketWebsite.websiteEndpoint;

        this.registerOutputs({
            endpoint: bucketWebsite.websiteEndpoint,
        });

Helper functions ​

In addition to the constructor logic, we also have a helper function allowGetObjectPolicy:

Example: StaticPage.ts a helper function

ts
    allowGetObjectPolicy(bucketName: string) {
        return JSON.stringify({
            Version: "2012-10-17",
            Statement: [
                {
                    Effect: "Allow",
                    Principal: "*",
                    Action: ["s3:GetObject"],
                    Resource: [`arn:aws:s3:::${bucketName}/*`],
                },
            ],
        });
    }

This function is used to create a S3 policy document, allowing public access to the objects in our bucket. It will be invoked within the context of apply(...). That means that the bucketName, which is normally a pulumi.Output<string> value, can be materialized as a normal TypeScript string, and is passed into this function that way. Note that you can't modify the value of bucketName, but you can read the value and use it to construct the policy document. The JSON.stringify(...) function takes the object as input and returns it as a JSON formatted string.

Use the Component in a Pulumi Program ​

You can either reference the component directly from a Pulumi program in the same language, or package it for distribution so it can be consumed from any Pulumi-supported language. See Packaging Components for the packaging options and how to choose between them.

Implementation details ​

The walkthrough above demonstrated a complete component implementation. The sections below cover the rules and requirements in detail as a reference. Define the arguments first, then write the component resource that consumes them, then add child resources, outputs, and any provider configuration.

Component arguments and type requirements ​

When packaging a component as a Pulumi plugin package, the arguments class has specific requirements due to schema generation and serialization. These constraints ensure component arguments can be transmitted to the Pulumi engine and reconstructed in the consumer's language when the component is consumed from a different language than it was authored in. Components used directly in the same language (without packaging) can be more flexible, but following these guidelines keeps the door open to packaging later.

Args shape

Define your args as a TypeScript interface. The analyzer rejects classes and type aliases. The interface doesn't need to be exported, but it must be reachable from the entry point through normal imports.

typescript
export interface MyComponentArgs {
    name: pulumi.Input<string>;
    count?: pulumi.Input<number>;
}

Supported types

  • string, number, boolean
  • T[] arrays
  • Index-signature objects: { [key: string]: T }
  • pulumi.Input<T>, pulumi.Output<T>
  • Nested interfaces
  • pulumi.Asset, pulumi.Archive
  • Resource types
  • Partial<T>, Required<T>
  • Enums — both the enum keyword and the "as const object" pattern are recognized:
typescript
enum MyEnum { Value1 = "Value1", Value2 = "Value2" }

const MyEnum = { Value1: "Value1", Value2: "Value2" } as const;
type MyEnum = typeof MyEnum[keyof typeof MyEnum];

Optional vs required

Use ?: or | undefined. | null alone is not optional — strict null checks are enabled, so null and undefined are distinct.

Unsupported types

  • Arbitrary union types beyond T | undefined, Input<T>, Output<T>, Partial<T>, and Required<T>
  • Functions and callbacks (they can't be represented in the schema)
typescript
// ❌ Won't work — union types and functions are not supported
export interface MyComponentArgs {
    value: string | number;  // Union — unsupported
    callback: () => void;    // Function — unsupported
}

// ✅ Use primitives wrapped in Input types
export interface MyComponentArgs {
    value: pulumi.Input<string>;
    count: pulumi.Input<number>;
}

Naming

Field names pass through to the schema verbatim — myFoo becomes myFoo, not my_foo. Use camelCase, which matches both the TypeScript convention and the schema convention.

Best practices

  • Wrap every scalar in pulumi.Input<T> so consumers can pass plain values or outputs from other resources without apply.
  • Mark optional fields with ?: and document their default behavior.
  • Keep the args interface flat — deeply nested structures make components harder to use.

Defining a component resource ​

Once your arguments are defined, write the component itself. The pattern differs by language: TypeScript, Python, .NET, and Java use a class with a constructor; Go uses a struct paired with a factory function (Go has no constructors); YAML uses a declarative definition (no class) under the components key.

In all cases, the component must register a unique type name with the engine. The type name takes the form <package-name>:<module>:<component-class-name>, where the module is usually index. Type names are namespaced alongside non-component resources such as aws:lambda:Function.

WARNING

Changing the type name after a component has been deployed will cause Pulumi to recreate every existing resource of that type. Settle on a name early.

Inside the constructor (or factory function), allocate any child resources, passing the component itself as the parent option so they appear under the component in the resource graph and inherit provider configuration.

Required signature by language ​

Each language has specific requirements for the component's entry point so that schema can be generated correctly when the component is packaged as a Pulumi plugin.

Requirements:

  • The constructor must have an argument named exactly args
  • The args parameter must have a type declaration (e.g., args: MyComponentArgs)
typescript
class MyComponent extends pulumi.ComponentResource {
    constructor(name: string, args: MyComponentArgs, opts?: pulumi.ComponentResourceOptions) {
        super("pkg:index:MyComponent", name, args, opts);
    }
}

The base call (super / base / ctx.RegisterComponentResource) registers the component instance with the Pulumi engine, recording its state and tracking it across deployments — even though component resources have no provider logic of their own, they still appear as resources you can diff and inspect.

Creating child resources ​

Component resources contain child resources. Child resource names must include the component resource's name as part of their names (e.g., as a prefix). This ensures uniqueness across multiple instances of the component and ensures that if the component is renamed, the child resources are renamed as well. Also, when constructing a resource, children must be registered as such. To do this, pass the component resource itself as the parent option.

This example demonstrates both the naming convention and how to designate the component resource as the parent:

typescript
class MyComponent extends pulumi.ComponentResource {
    bucket: aws.s3.Bucket;

    constructor(name: string, myComponentArgs: MyComponentArgs, opts: pulumi.ComponentResourceOptions) {
        super("pkg:index:MyComponent", name, {}, opts);

        // Create Child Resource
        this.bucket = new aws.s3.Bucket(`${name}-bucket`,
            {}, { parent: this });
    }
}

WARNING

Always set parent when creating resources inside a component. Omitting it causes the following problems:

  • Resource graph: Child resources won't appear under the component in pulumi preview and the Pulumi Cloud console, making the resource hierarchy unclear.
  • Provider inheritance: Child resources won't automatically inherit provider configuration (such as region or credentials) passed to the component via the providers option.
  • Dependency tracking: Other resources that depend on the component won't automatically wait for un-parented resources to finish creating, which can cause race conditions or incomplete deployments.

Registering component outputs ​

Component resources can define their own output properties. Outputs in a component must be registered with the Pulumi IaC engine by calling registerOutputs. The Pulumi engine uses this information to display the logical outputs of the component resource and any changes to those outputs will be shown during an update.

For example, this code registers an S3 bucket's computed domain name, which won't be known until the bucket is created:

typescript
class MyComponent extends pulumi.ComponentResource {
    bucket: aws.s3.Bucket;

    constructor(name: string, myComponentArgs: MyComponentArgs, opts: pulumi.ComponentResourceOptions) {
        super("pkg:index:MyComponent", name, {}, opts);

        this.bucket = new aws.s3.Bucket(`${name}-bucket`,
            {}, { parent: this });

        // Registering Component Outputs
        this.registerOutputs({
            bucketDnsName: this.bucket.bucketDomainName
        });
    }
}

The call to registerOutputs typically happens at the very end of the component's constructor (or factory function, in Go).

What registerOutputs does ​

The registerOutputs call serves two purposes:

  1. Marks the component as fully constructed: It signals to the Pulumi engine that the component resource has finished registering all its child resources and should be considered complete.
  2. Saves outputs to state: It saves the component's output properties to the state file so they appear in the Pulumi Cloud console and CLI.

WARNING

Always call registerOutputs, even when you have no outputs to register (pass an empty object). Without this call:

  • Resource hooks such as afterCreate will not fire on the component. Hooks are often used for security, compliance, or notification logic, so silently skipping them can be harmful.
  • The component will appear as "creating..." in the CLI and Pulumi Cloud console until the entire deployment completes, rather than when the component itself finishes.
  • The component's output properties will not be saved to the state file. (Child resource state is unaffected.)

INFO

.NET: Since pulumi-dotnet 3.59.0, calling RegisterOutputs() without arguments automatically registers all properties decorated with [Output].

Passing resource options to components ​

Like any resource, a component accepts a third argument of resource options when it's instantiated. Some options are component-only (notably providers, which lets a consumer target the component at a specific provider configuration).

WARNING

Not all resource options apply to component resources. For example, ignoreChanges and customTimeouts have no effect on components themselves. To see which options work with components and how to apply options to child resources using transforms, see Resource options and component resources.

The providers option is the most common reason to pass options to a component instance — it flows the consumer's chosen provider configuration through to every child resource the component creates. See the providers resource option for details and a worked example targeting one component at multiple provider configurations from a single program.

Evolving a component ​

When a new component version changes how its children are represented in state, use state migrations to translate the prior state before Pulumi calculates changes. For changes to resource names or parents that do not require translating saved properties, use aliases.

Next steps ​

Now that you've written a component, the next step is to package it so it can be installed and used from any Pulumi program in any supported language.

  • Authoring a Source-Based Plugin Package — wrap the component class you just wrote in the project layout (PulumiPlugin.yaml, language manifest, entry file) that makes it installable via pulumi package add. This is the recommended next step for most component authors.
  • Packaging Components — compares the source-based, native-language, and executable-based plugin approaches if you're not sure which fits your use case.
  • Testing Components — strategies for testing component behavior.

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