CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-pulumi--pulumi

Pulumi's Node.js SDK for infrastructure-as-code platform that allows you to create, deploy, and manage infrastructure using familiar programming languages and tools.

85

1.02x
Overview
Eval results
Files

runtime-operations.mddocs/

Runtime Operations

Pulumi's runtime system provides low-level functions for resource registration, serialization, state management, and execution orchestration. These functions are typically used by provider implementations and advanced use cases.

Resource Registration

function registerResource(
  res: Resource,
  type: string,
  name: string,
  props: Inputs,
  opts?: ResourceOptions,
  remote?: boolean
): Promise<void>;

function registerResourceOutputs(
  res: Resource,
  outputs: Inputs | Promise<Inputs> | Output<Inputs> | undefined
): void;

function readResource(
  res: Resource,
  type: string,
  name: string,
  props: Inputs,
  opts: ResourceOptions,
  remote?: boolean
): Promise<void>;

function getResource(
  res: Resource,
  type: string,
  name: string,
  props: Inputs,
  opts: ResourceOptions
): Promise<void>;

Invoke Operations

function invoke(
  token: string,
  props: Inputs,
  opts?: InvokeOptions,
  res?: Resource
): Promise<any>;

function invokeOutput(
  token: string,
  props: Inputs,
  opts?: InvokeOutputOptions
): Output<any>;

function invokeSingle(
  token: string,
  props: Inputs,
  opts?: InvokeOptions
): Promise<any>;

function invokeSingleOutput(
  token: string,
  props: Inputs,
  opts?: InvokeOutputOptions
): Output<any>;

function call(
  token: string,
  props: Inputs,
  res?: Resource
): Promise<any>;

function callSingle(
  token: string,
  props: Inputs,
  res?: Resource
): Promise<any>;

Invoke Options

interface InvokeOptions {
  parent?: Resource;
  provider?: ProviderResource;
  version?: string;
  pluginDownloadURL?: string;
  async?: boolean;
}

interface InvokeOutputOptions extends InvokeOptions {
  dependsOn?: Input<Input<Resource>[]> | Input<Resource>;
}

Configuration Management

function allConfig(): {[key: string]: string};
function setAllConfig(c: {[key: string]: string}, secretKeys?: string[]): void;
function setConfig(k: string, v: string): void;
function getConfig(k: string): string | undefined;
function isConfigSecret(k: string): boolean;

State Management

function getStackResource(): Stack | undefined;
function setStackResource(newStackResource?: Stack): void;
function getStore(): Map<any, any>;
function getLocalStore(): Map<any, any>;
function getGlobalStore(): Map<any, any>;

Runtime Settings

function isDryRun(): boolean;
function getProject(): string;
function getStack(): string;
function getOrganization(): string;
function getRootDirectory(): string;
function hasMonitor(): boolean;
function getMonitor(): any;
function hasEngine(): boolean;
function getEngine(): any;

Serialization System

function serializeResourceProperties(
  label: string,
  props: Inputs,
  opts?: SerializationOptions
): Promise<any>;

function serializeProperties(
  label: string,
  props: Inputs,
  opts?: SerializationOptions
): Promise<any>;

function deserializeProperties(
  outputsStruct: any,
  keepUnknowns?: boolean
): any;

function serializeProperty(
  prop: Input<any>,
  labels: Set<Resource>,
  dependsOn: Resource[],
  secret: boolean,
  opts?: SerializationOptions
): any;

function deserializeProperty(prop: any, keepUnknowns?: boolean): any;

interface SerializationOptions {
  keepOutputValues?: boolean;
  keepSecrets?: boolean;
  keepResources?: boolean;
}

Mocking System

function setMocks(
  mocks: Mocks,
  project?: string,
  stack?: string,
  preview?: boolean
): void;

interface Mocks {
  newResource?: (args: MockResourceArgs) => MockResourceResult;
  call?: (args: MockCallArgs) => MockCallResult;
}

interface MockResourceArgs {
  type: string;
  name: string;
  inputs: any;
  provider?: string;
  id?: string;
}

interface MockResourceResult {
  id?: string;
  state?: any;
}

interface MockCallArgs {
  token: string;
  inputs: any;
  provider?: string;
}

interface MockCallResult {
  result?: any;
}

class MockMonitor {
  // Mock implementation for testing
}

Closure Serialization

function serializeFunction(func: Function, args?: any): Promise<string>;
function serializeFunctionAsync(func: Function, serialize?: boolean): Promise<string>;
function computeCodePaths(options?: any): Promise<string[]>;

Constants and Utilities

const unknownValue: any;
const specialSigKey: string;
const specialAssetSig: string;
const specialArchiveSig: string;
const specialSecretSig: string;
const specialResourceSig: string;
const specialOutputValueSig: string;

Usage Examples

Custom Resource Implementation

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

class CustomS3Bucket extends pulumi.CustomResource {
  public readonly bucketName!: pulumi.Output<string>;
  public readonly arn!: pulumi.Output<string>;

  constructor(name: string, args: S3BucketArgs, opts?: pulumi.CustomResourceOptions) {
    const props: any = {
      bucketName: args.bucketName,
      region: args.region,
    };

    super("custom:s3:Bucket", name, props, opts);
  }
}

interface S3BucketArgs {
  bucketName?: pulumi.Input<string>;
  region?: pulumi.Input<string>;
}

// Register the resource
runtime.registerResource(
  new CustomS3Bucket("my-bucket", { bucketName: "my-custom-bucket" }),
  "custom:s3:Bucket",
  "my-bucket",
  { bucketName: "my-custom-bucket" }
);

Invoke Function Usage

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

// Invoke a provider function
const result = await runtime.invoke("aws:s3/getBucket:getBucket", {
  bucket: "my-bucket-name",
});

console.log("Bucket region:", result.region);

// Invoke with Output result
const bucketInfo = runtime.invokeOutput("aws:s3/getBucket:getBucket", {
  bucket: pulumi.output("my-bucket-name"),
});

export const bucketRegion = bucketInfo.region;

Configuration Access

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

// Get all configuration
const allConfig = runtime.allConfig();
console.log("All config:", allConfig);

// Set configuration programmatically
runtime.setConfig("myapp:environment", "production");
runtime.setConfig("myapp:debug", "false");

// Check if config is secret
if (runtime.isConfigSecret("myapp:apiKey")) {
  console.log("API key is stored as secret");
}

Testing with Mocks

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

// Set up mocks for testing
runtime.setMocks({
  newResource: (args) => {
    switch (args.type) {
      case "aws:s3/bucket:Bucket":
        return {
          id: `${args.name}-id`,
          state: {
            bucket: args.inputs.bucket || `${args.name}-bucket`,
            arn: `arn:aws:s3:::${args.inputs.bucket || args.name}`,
          },
        };
      default:
        return { id: `${args.name}-id`, state: args.inputs };
    }
  },
  call: (args) => {
    switch (args.token) {
      case "aws:index/getRegion:getRegion":
        return { result: { name: "us-east-1" } };
      default:
        return { result: {} };
    }
  },
}, "test-project", "test-stack", false);

// Now create resources - they will use mocks
const bucket = new aws.s3.Bucket("test-bucket", {
  bucket: "test-bucket-name",
});

// Test assertions
bucket.id.apply(id => {
  console.assert(id === "test-bucket-id", "Expected mocked ID");
});

Serialization Examples

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

// Serialize resource properties
const serialized = await runtime.serializeProperties("test", {
  name: "my-resource",
  count: pulumi.output(5),
  config: {
    enabled: true,
    tags: ["prod", "web"],
  },
});

console.log("Serialized properties:", serialized);

// Deserialize properties
const deserialized = runtime.deserializeProperties({
  name: "my-resource",
  count: { sig: "cGx1bWk6c3RhY2s=", value: 5 },
});

console.log("Deserialized properties:", deserialized);

State Management

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

// Access runtime state
const stackResource = runtime.getStackResource();
if (stackResource) {
  console.log("Stack resource available");
}

// Use runtime stores for caching
const globalStore = runtime.getGlobalStore();
globalStore.set("cached-value", { timestamp: Date.now(), data: "value" });

const cachedValue = globalStore.get("cached-value");
console.log("Cached value:", cachedValue);

// Check runtime mode
if (runtime.isDryRun()) {
  console.log("Running in preview mode");
} else {
  console.log("Running actual deployment");
}

Function Serialization

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

// Serialize function for remote execution
const handler = async (event: any) => {
  console.log("Processing event:", event);
  return { statusCode: 200, body: "Hello World" };
};

const serializedFunction = await runtime.serializeFunction(handler, {
  dependencies: ["some-module"],
});

console.log("Serialized function:", serializedFunction);

// Compute code paths for packaging
const codePaths = await runtime.computeCodePaths({
  excludePackages: ["aws-sdk"],
});

console.log("Code paths to include:", codePaths);

Best Practices

  • Use runtime functions primarily in provider implementations
  • Handle serialization errors gracefully
  • Use mocks extensively for unit testing
  • Cache expensive serialization operations when possible
  • Be careful with direct state manipulation functions
  • Use appropriate serialization options for your use case
  • Test function serialization thoroughly before deployment
  • Monitor runtime performance in production
  • Use configuration functions for dynamic provider configuration
  • Implement proper error handling for invoke operations
  • Use type assertions when deserializing properties
  • Clean up stores and caches appropriately

Install with Tessl CLI

npx tessl i tessl/npm-pulumi--pulumi

docs

asset-management.md

automation.md

configuration.md

dynamic-resources.md

index.md

logging-diagnostics.md

output-system.md

provider-development.md

resource-management.md

runtime-operations.md

stack-references.md

utilities.md

tile.json