Accessing single outputs with Apply
The apply method is used to access the plain value of a single output and perform operations on it. Because outputs are asynchronous values that only become known after a resource has finished provisioning, you cannot directly access or manipulate their values using standard language operations (like printing or string concatenation). The apply method solves this by waiting for the output value to become available and then executing a function with that plain value.
The apply method is typically used for:
- Printing output values for debugging Pulumi programs
- Accessing nested values in complex types (outputs that are objects or dictionaries)
- Transforming an output by referencing its plain value
- Converting inputs to outputs to call
applyon a value typed asInput<T>
For more information about what outputs are and why they are necessary in Pulumi programs, see Inputs and Outputs.
INFO
The apply method is designed for accessing single output values. If you need to access multiple output values across multiple resources, use Pulumi's all method instead.
INFO
Seeing placeholder text like Calling [toString] on an [Output<T>] is not supported in a log line, a generated file, or a resource property instead of the value you expected? See Output value errors for a rundown of this and other symptoms of treating an output as if it were already a plain value.
WARNING
Creating resources inside an apply should be avoided whenever possible. Resources created inside apply will not appear in pulumi preview unless the output's value is already known. This means the preview output may not match the actual changes when pulumi up is run, making it difficult to understand what changes will be made to your infrastructure.
If you need to create a resource that depends on an output value, pass the output directly as an input to the resource instead of using apply. Pulumi will automatically handle the dependency tracking and ensure resources are created in the correct order.
WARNING
You cannot create stack outputs (using export in TypeScript/JavaScript, pulumi.export() in Python, ctx.Export() in Go, etc.) inside an apply. Stack outputs must be created at the top level of your Pulumi program. If you need to export a value that depends on an output, you can export the output directly—Pulumi will automatically handle resolving the value when the stack output is accessed.
INFO
The apply method does not apply to Pulumi YAML. YAML is a declarative language with no facility for running a function against a resolved value, so it has no apply equivalent. To use an output value in a YAML program, reference it directly with interpolation syntax (for example, ${myResource.myProperty}) and Pulumi resolves the value for you. For this reason, the examples on this page do not include YAML.
Printing output values
Suppose you want to print the ID of a resource you've created. These kinds of values are outputs—values that cannot be known until after a resource is provisioned. You might try logging the value like you would any other string:
import * as pulumi from "@pulumi/pulumi";
import * as awsx from "@pulumi/awsx";
const vpc = new awsx.ec2.Vpc("vpc");
console.log(vpc.vpcId);However, if you run the program as shown with pulumi up, you will receive something like the following CLI output:
# Example CLI output (truncated)
Diagnostics:
pulumi:pulumi:Stack (aws-js-dev):
OutputImpl {
__pulumiOutput: true,
resources: [Function (anonymous)],
allResources: [Function (anonymous)],
isKnown: Promise { <pending> },
isSecret: Promise { <pending> },
promise: [Function (anonymous)],
toString: [Function (anonymous)],
toJSON: [Function (anonymous)]
}This is where
Apply
Apply
To print out the value of the VPC ID, use the apply function:
import * as pulumi from "@pulumi/pulumi";
import * as awsx from "@pulumi/awsx";
const vpc = new awsx.ec2.Vpc("vpc");
vpc.vpcId.apply(id => console.log(`VPC ID: ${id}`));The above example will wait for the value to be returned from the API and print it to the console as shown below:
Updating (pulumi/dev)
Type Name Status Info
pulumi:pulumi:Stack aws-iac-dev 1 message
Diagnostics:
pulumi:pulumi:Stack (aws-iac-dev):
VPC ID: vpc-0f8a025738f2fbf2fAccessing nested output values
Sometimes a resource has an output property that is an array or a more complex object with multiple levels of nested values. Consider, for example, this AWS Certificate Manager certificate resource:
import * as aws from "@pulumi/aws";
const zone = new aws.route53.Zone("zone", {
name: "example.com",
});
const cert = new aws.acm.Certificate("cert", {
domainName: "example.com",
validationMethod: "DNS",
});This resource will have outputs that resemble the following:
# Example truncated output of the ACM certificate resource
cert: {
arn : "arn:aws:acm:eu-central-1..."
certificate_authority_arn: ""
certificate_body : <null>
certificate_chain : <null>
domain_name : "example.com"
domain_validation_options: [
[0]: {
domain_name : "example.com"
resource_record_name : "_0a822dde6347292b.example.com."
resource_record_type : "CNAME"
resource_record_value: "_527b1cdf2159204b.mhbtsbpdnt.acm-validations.aws."
}
]
...
...
}Suppose you want to validate your certificate by creating an Amazon Route 53 record. To do so, you will need to retrieve the value of the resource record from the ACM certificate. This value is nested in the domain validation options property of the certificate resource, which is an array. Because that value is an output, you would normally need to use
Apply
// Using apply to access nested output values
const certValidationApply = new aws.route53.Record("certValidationApply", {
name: cert.domainValidationOptions.apply(
domainValidationOptions => domainValidationOptions[0].resourceRecordName),
type: cert.domainValidationOptions.apply(
domainValidationOptions => domainValidationOptions[0].resourceRecordType),
zoneId: zone.zoneId,
ttl: 60,
records: [
cert.domainValidationOptions.apply(
domainValidationOptions => domainValidationOptions[0].resourceRecordValue),
],
});Using lifting to simplify nested access
An easier way to access deeply nested properties is by using lifting. Lifting allows you to access properties and elements directly from a
Output<T>
Apply
Lifting is handled automatically by Pulumi's type system, so in most cases you don't need to think about it. When you access a property or array element on an output value, Pulumi automatically "lifts" that access into the output context, returning a new output that will resolve to that nested value. This approach is easier to read and write and does not lose any important dependency information that is needed to properly create and maintain the stack.
INFO
Lifting works in most scenarios for accessing nested properties and array elements. However, you may occasionally encounter runtime errors with lifting depending on your language. For example, in TypeScript, if an output resolves to undefined, using lifting to reference outputThatResolvesToUndefined.someProperty doesn't raise an error; it returns an output that also resolves to undefined. When you need to detect or handle a missing value, use apply with appropriate null checking instead.
Returning to the certificate validation example from the previous section, you can use lifting to simplify the code as shown below:
// Using lifting to access nested output values
const certValidationLifting = new aws.route53.Record("certValidationLifting", {
name: cert.domainValidationOptions[0].resourceRecordName,
type: cert.domainValidationOptions[0].resourceRecordType,
zoneId: zone.zoneId,
ttl: 60,
records: [
cert.domainValidationOptions[0].resourceRecordValue,
],
});Creating new output values
Outputs and strings
Outputs that return to the engine as strings cannot be used directly in operations such as string concatenation until the output value has returned to Pulumi. In these scenarios, you'll need to wait for the value to return using apply.
INFO
For the common case of building a string from output values, Pulumi's output helpers provide a more concise alternative that doesn't require calling apply directly.
For example, the following code creates an HTTPS URL from the DNS name (the plain value) of a virtual machine (in this case an EC2 instance):
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const server = new aws.ec2.Instance("web-server", {
ami: "ami-0319ef1a70c93d5c8",
instanceType: "t2.micro",
});
const url = server.publicDns.apply(dnsName => `https://${dnsName}`);
export const InstanceUrl = url;The CLI output of this code would look something like the following:
Updating (pulumi/dev)
Type Name Status
pulumi:pulumi:Stack aws-iac-dev
- └─ awsx:ec2:Vpc vpc
Outputs:
InstanceUrl: "https://ec2-52-59-110-22.eu-central-1.compute.amazonaws.com"
Duration: 5sThe returned value of the call to
Apply
pulumi.Output<string>, meaning the `url` variable is now of an Output. This variable will wait for the new value to be returned from the Apply
pulumi.Output<string>. Outputs and JSON
Many cloud resources require JavaScript Object Notation (JSON) documents, such as policies that control access to resources. The Pulumi SDK provides helper methods in most languages to make it easier to work with Pulumi outputs and JSON documents. These helper methods have similar names and function signatures to their plain-value analogues. For a consolidated reference of all JSON helpers, see Using output helpers.
Converting JSON objects to strings
If you need to construct a JSON string using output values from Pulumi resources, you can do so using a JSON stringify helper that is defined in the Pulumi SDK. These helpers unwrap Pulumi outputs without requiring the use of apply and produce JSON string outputs suitable for passing to other resources as inputs.
The following example demonstrates using helper methods for JSON serialization:
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Get the account ID of the current user as a Pulumi output.
const accountID = aws.getCallerIdentityOutput().accountId;
// Create an S3 bucket.
const bucket = new aws.s3.Bucket("my-bucket");
// Create an S3 bucket policy allowing anyone in the account to list the contents of the bucket.
const policy = new aws.s3.BucketPolicy("my-bucket-policy", {
bucket: bucket.id,
policy: pulumi.jsonStringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Principal: {
AWS: pulumi.interpolate`arn:aws:iam::${accountID}:root`,
},
Action: "s3:ListBucket",
Resource: bucket.arn,
},
],
}),
});
// Export the name of the bucket.
export const bucketName = bucket.id;When constructing a JSON policy document, it is often necessary to build a resource identifier by appending a path suffix to an output value. For example, Amazon S3 bucket policies that apply to objects rather than to the bucket itself require a resource ARN ending in /*. Because the bucket ARN is a Pulumi output, you must combine the JSON stringify helper with your language's string interpolation facility to produce the correct value.
The following example demonstrates this pattern, using the bucket's ARN as a base and appending /* to target all objects in the bucket:
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Create an S3 bucket.
const bucket = new aws.s3.Bucket("my-bucket");
// Create an S3 bucket policy that grants read access to all objects in the bucket.
// The Resource field uses pulumi.interpolate to append "/*" to the bucket ARN,
// targeting individual objects rather than the bucket itself.
const policy = new aws.s3.BucketPolicy("my-bucket-policy", {
bucket: bucket.id,
policy: pulumi.jsonStringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Principal: "*",
Action: "s3:GetObject",
Resource: pulumi.interpolate`${bucket.arn}/*`,
},
],
}),
});
// Export the name of the bucket.
export const bucketName = bucket.id;Converting JSON strings to outputs
If you have an output in the form of a JSON string and you need to interact with it like you would a regular JSON object, you can use Pulumi's parsing helper function.
The following example shows how to use a helper method to parse an IAM policy defined as a pulumi.Output<string> into a native object and then manipulate that object to remove all of the policy statements:
import * as pulumi from "@pulumi/pulumi";
const jsonIAMPolicy = pulumi.output(`{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"s3:ListAllMyBuckets",
"s3:GetBucketLocation"
],
"Resource": "*"
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": "s3:*",
"Resource": "arn:aws:s3:::my-bucket"
}
]
}`);
// Parse the string output.
const policyWithNoStatements: pulumi.Output<object> = pulumi.jsonParse(jsonIAMPolicy).apply(policy => {
// Empty the policy's Statements list.
policy.Statement = [];
return policy;
});
// Export the modified policy.
export const policy = policyWithNoStatements;For more details view the Node.js documentation.
Handling errors in apply
The function you pass to
Apply
How you signal an error from the callback depends on the language.
Throw an exception from the callback (or return a rejected promise). The thrown error rejects the resulting output and fails the update.
const validated = name.apply(n => {
if (!n.includes("a")) {
throw new Error(`name "${n}" must contain the letter 'a'`);
}
return n;
});The update fails even if validated is never used later in the program.
To handle a potential failure gracefully and continue rather than failing the update, do the handling inside the callback—for example, catch the error and return a fallback value instead of raising.
Converting inputs to outputs
Resource arguments in Pulumi accept Input<T> values, which means they will take either a plain value or an Output<T>. In most programs this flexibility is all you need. Occasionally, though, you have a value typed as Input<T> and need a definite Output<T>—most commonly to call apply on it.
This situation arises most often in the following cases:
- Writing a component resource. Component constructors typically accept
Input<T>parameters to give callers the flexibility to pass either a plain value or an existing output. Inside the component body, you often need to callapplyor chain other output operations on those parameters, which requiresOutput<T>. - Writing utility functions that accept
Input<T>. A function that acceptsInput<T>for caller flexibility must convert toOutput<T>internally before it can callapplyto perform any transformation. - Combining values with
all. While theallfunction accepts a mix of plain values and outputs in most SDKs, explicitly converting to outputs first can make your program’s data flow clearer and more predictable.
Pulumi's SDKs provide a dedicated function to wrap any Input<T> as a guaranteed Output<T>:
pulumi.output() accepts any Input<T>—a plain value or an existing Output<T>—and returns Output<T>. The example below defines a helper that requires Output<string> internally, then calls it with both a plain string and with an Output<string> from a resource to show that both work.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
function buildUrl(host: pulumi.Input<string>): pulumi.Output<string> {
return pulumi.output(host).apply(h => `https://${h}`);
}
const fromPlain = buildUrl("example.com");
const bucket = new aws.s3.Bucket("my-bucket");
const fromOutput = buildUrl(bucket.bucketRegionalDomainName);When the value you pass is already an Output<T>, the conversion function returns it unchanged. When you pass a plain value, Pulumi wraps it in a new output that resolves immediately with that value. In either case, the result is a definite Output<T> on which you can call apply or any other output method.