pulumi: Allow applications to handle "not found" errors from `.get()`

Problem Scenario

It can be common to need to query for an existing resource and if it doesn’t exist then take some other action. Currently Pulumi’s <resource>.get() methods halt Pulumi execution without throwing an error that the user/application can catch and react to.

Suggestion

The results or error from <resource>.get() calls and data sources should be catchable so that users can take other actions as a result.

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Reactions: 89
  • Comments: 38 (13 by maintainers)

Most upvoted comments

+1 any updates on this one? Really need the get to be “catchable”. The scenario I want to accomplish is as follows

  • use .get() to lookup the resource.
  • if the resource does not exists, there is an exception thrown,
  • Catch the exception in the catch block and create a new resource there.

I never understood fully why this can’t be fixed. I spent a few minutes just now, and though it’s tricky, I do think there are a combination of changes we could make to address this:

  1. Enable ReadResource to fail gracefully when a resource is missing. Right now, it just errors out in the step execution, which triggers a failure in the engine. This requires some thought as to the gRPC interface. The following is a clunky targeted change, but it works:

    diff --git a/pkg/resource/deploy/source_eval.go b/pkg/resource/deploy/source_eval.go
    index 9e890bdf7..e4025cdd8 100644
    --- a/pkg/resource/deploy/source_eval.go
    +++ b/pkg/resource/deploy/source_eval.go
    @@ -1381,8 +1381,14 @@ func (rm *resmon) ReadResource(ctx context.Context,
     		logging.V(5).Infof("ResourceMonitor.ReadResource operation canceled, name=%s", name)
     		return nil, rpcerror.New(codes.Unavailable, "resource monitor shut down while waiting on step's done channel")
        }
    -
     	contract.Assertf(result != nil, "ReadResource operation returned a nil result")
    +
    +	// If the state is nil, which means it wasn't found, return an error in the response.
    +	if result.State.Outputs == nil {
    +		return nil, rpcerror.New(codes.InvalidArgument,
    +			fmt.Sprintf("resource %s of type %s with ID %s was not found", name, t, id))
    +	}
    +
     	marshaled, err := plugin.MarshalProperties(result.State.Outputs, plugin.MarshalOptions{
     		Label:            label,
     		KeepUnknowns:     true,
    @@ -1393,7 +1399,6 @@ func (rm *resmon) ReadResource(ctx context.Context,
     	if err != nil {
        	return nil, fmt.Errorf("failed to marshal %s return state: %w", result.State.URN, err)
     	}
    -
     	return &pulumirpc.ReadResourceResponse{
     		Urn:        string(result.State.URN),
     		Properties: marshaled,
    diff --git a/pkg/resource/deploy/step.go b/pkg/resource/deploy/step.go
    index a01afab1f..d1626dfef 100644
    --- a/pkg/resource/deploy/step.go
    +++ b/pkg/resource/deploy/step.go
    @@ -887,8 +887,10 @@ func (s *ReadStep) Apply() (resource.Status, StepCompleteFunc, error) {
     
     		// If there is no such resource, return an error indicating as such.
     		if result.Outputs == nil {
    -			return resource.StatusOK, nil, fmt.Errorf("resource '%s' does not exist", id)
    +			s.new.Outputs = nil
    +			return resourceStatus, func() { s.event.Done(&ReadResult{State: s.new}) }, nil
     		}
    +
     		s.new.Outputs = result.Outputs
     
     		if result.ID != "" {
    

    Most likely we’d want to think about an opt-in to this new failure mode and/or returning something in the response payload rather than abusing codes.InvalidArgument in this way. The engine also needs to “forget” a resource that triggers this behavior.

  2. Adding a new variant of get methods – call it getAsync – that returns a promise which breaks when the resource wasn’t found. For example, we have get(...): Bucket, and this new method would be getAsync(...): Promise<Bucket>.

  3. That method internally just does what get does today, except that it internally awaits the resource URN’s promise().

  4. There were quite a few places in the language SDK where we assume that if a failure occurs in this manner, we want to terminate the program. That’s probably an argument for a first class property in the ReadResource result, rather than abusing gRPC errors. We, of course, still want to fail most of the time, but not when getAsync observed and communicated the error. An assortment of edits to the various promise error handling facilities in the TypeScript SDK, at least, was sufficient to get this working.

I was able to hack together a quick proof of concept, and indeed I was able to write this program:

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

// Create an AWS resource (S3 Bucket)
console.log("Before getAsync");
try {
    const bucket = await aws.s3.BucketV2.getAsync("my-bucket", "a-bucket-that-...-doesnt-exist");
    console.log("After getAsync");
} catch (e) {
    console.log("Caught and ignoring: " + e);
}

And have it run w/out failure:

$ pulumi up
Previewing update (dev)

     Type                 Name               Plan       Info
 +   pulumi:pulumi:Stack  catchable-get-dev  create     2 messages

Diagnostics:
  pulumi:pulumi:Stack (catchable-get-dev):
    Before getAsync
    Caught and ignoring: failed to read resource #a-bucket-that-...-doesnt-exist 'my-bucket' [aws:s3/bucketV2:BucketV2]: 3 INVALID_ARGUMENT: resource my-bucket of type aws:s3/bucketV2:BucketV2 with ID a-bucket-that-...-doesnt-exist was not found

Resources:
    + 1 to create

Do you want to perform this update?
> yes
  no
  details

The pattern of create-if-not-exist would presumably want to allocate a "my-bucket" in the catch, but that doesn’t work without deeper changes alluded to above, such as forgetting about a ReadResource if it wasn’t found during lookup. The code suggests this was the original intent, but it doesn’t seem to do so. I assume it is imminently possible.

We’re actively working on it, but it’s a subtle problem.

I have a similar use case which cannot be covered with “create if not exists” pattern.

const helm_postgres = new kubernetes.helm.v3.Release(
  "helm-postgres",
  // ...
  { ignoreChanges: ["checksum"] }
);

const secret_postgres = pulumi.output(
  kubernetes.core.v1.Secret.get("helm-postgres-secret", "postgres/postgres-postgresql")
);

I have a database deployed with helm, and I have to read out the secrets created by the chart to get the connection password (which is then passed to other resources I wanted to create).

Same issue here with an attempt to create k8s namespace.

Is there any progress on this one?

no fix for this after 5 years?

I had a very similar ‘user story’:

  • I triggered a Kubernetes operator via a CRD to do its job.
  • It creates a whole a bunch of resources, including some secrets.
  • In order for Pulumi to continue, I need the certificate of those secrets to properly configure a plugin. It needs the certificate to authenticate with the new instance created by the operator.

My current workaround - waiting several minutes before attempting to read the resource - is not very cool and often adds unnecessary delay to the enrollment process.

Is there any way to lookup for the existence of a resource without the function actually throwing an error? For context - I am trying to get getUserAssignedIdentityOutput but it errors out and the error seems to be not catchable. https://www.pulumi.com/registry/packages/azure-native/api-docs/managedidentity/getuserassignedidentity/

Give the above & https://github.com/pulumi/pulumi/issues/11275 I think we should reopen this. We’ll need to be careful to explain that this can not be used for “try get or create” logic, but it sounds like it has other applications as well.

Updated to include “and data sources” in the suggestion.

For invokes (“data sources”), you can do this today:

aws.getAmi({
    owners: ["153052954103"],
}, { async: true })
.then(
    res => console.log(`RESULT: ${res}`), 
    err => console.error(`ERROR: ${err}`)
);

That is, the error is bubbled up through the promise error handler (and as an exception in async/await code).

Another example:

async function getAmi(): Promise<string> {
    try {
        const amiDetails = await aws.getAmi({
            owners: ["153052954103"],
        }, { async: true });
        return amiDetails.id;
    } catch (err) {
        return "ami-014a2e30da708ee8b";
    }
}

This is not true for .get() calls though (which is what I will continue to track with this issue).

Found this documentation reference for <resource>.get(): https://www.pulumi.com/docs/intro/concepts/resources/get/

Would it be possible to add <resource>.exists() with a similar signature to get() with the following constraints:

  • no exception if resource does not exist, return false (or Promise<Boolean>, or Output<Boolean>)

  • perhaps avoid serializing exists calls into the checkpoint file and avoid the issues with that

  • this is a non-breaking addition to the API

The user code would then be able to express patterns like this:

if RDSCluster.exists(...) {
   cluster = RDSCluster.get(...)
} else {
   cluster = new RDSCluster(...)
   createSchema(cluster.getConn())
}

This might cause some confusion as to how the program behaves in preview, specifically:

  • would the same code branch always be selected in preview and up against the same state?

  • would pulumi up result in empty pulumi preview? this might no longer be true for programs that switch to a different branch after a pulumi up and might be a tad confusing; this seems inevitable though with any solution that allows differential behavior asked for in the ticket

+1

Scenario: run a Lambda Function to create schema on an RDS Cluster only if the Cluster hasn’t existed before.

Bumping this issue to stay visible. I am currently working around this issue by commenting out code for initial runs of IaC.

any update on this ?

Very frustrating for use cases such as mine, i dynamically calculate storage needs for certain PVC’s and if i see i need to expand storage i apply a patch on the PVC.

I only want to apply the patch if the size of the storage is different then what is in the cluster. The issue is that i need to get the resource and inspect it’s size, when i run this before the resource is created, Pulumi CLI fails and requires me to comment out the code, and after that to uncomment it and run again.

I have a similar use case which cannot be covered with “create if not exists” pattern. … I have a database deployed with helm, and I have to read out the secrets created by the chart to get the connection password (which is then passed to other resources I wanted to create).

My use-case is similar. I am using an AWS lambda to create certificates and insert them into the secrets manager. One solution may be to pre-create placeholder secret entries, but that “doesn’t feel right”. It would be ideal if there were a mechanism in Pulumi to mark resources which may not exist at time of preview.

Thanks Pulumi team!

I have the same use case as @xfoxfu . My Pulumi program runs the Release resource to install a helm chart which creates a secret that I need to retrieve. I use the Secret.get() function, but now my preview keeps failing because that secret doesn’t exist yet. I tried using dependsOn: <myReleaseResource> on that get() function, but no avail.

A workaround would be to use Azure SDK to check if the resource exists before using the Get method.

+1 for that

After an investigation in #10883 and discussing the implications with @Frassle we are leaning to close this issue and recommend other Pulumi mechanisms for the use cases here:

  1. A lot of the readers coming here are interested in handling the error from get to create a resource if it does not already exist. #3388 will provide a much better way to address this scenario.

  2. There is a workaround available now before #3388 ships. Providers expose data sources allowing the program to query for existence of resources in the cloud. For an example see getSecurityGroups in AWS. The advantage of these compared to Resource.get() is that they do not interfere with Pulumi state.

  3. For use cases that need to run some logic when a resource actually gets created, lifecycle hooks (specifically create hooks) as specified in #1691 seem to be the preferable mechanism.


Technicalities from the #10338 exploration:

  • Explored building conditional creation on top of recoverable Resource.get in #10883. While it can be made to work, there are some challenges in this approach to get previews and repeated updates working correctly.

  • The engine sees Resource.tryGet()…new Resource() as two separate operations and not an atomic operation, confusing URN uniqueness tracking, requiring workarounds

  • Repeated update has to edit the resource’s record in the state to switch from the new Resource style record to a Resource.get style record (external: true), requiring workarounds to get empty previews and avoid UI glitches

Expereincing the same issue. Would like to create an AWS Config recorder (limited to 1 per account per region) and want to check if one already exists before attempting to create one.

const recorder = aws.cfg.Recorder.get('recorder', 'default'); // Halts Pulumi if it does not exist and unable to catch the error.