1. How to check if Pulumi called NewInstance twice?

    TypeScript

    Typically, Pulumi maintains the state of a stack and controls the lifecycle of resources in it. If aws.ec2.Instance (or similar resource) is invoked twice in your Pulumi program with different names, two distinct resources will be created. However, Pulumi will not allow the creation of two resources of the same type with the same name in a single Pulumi program.

    Here's an example which tries to create two EC2 instances using AWS in Pulumi. Please note that you have to replace <AMI_ID>, <ACCESS_KEY>, and <SECRET_ACCESS_KEY> with the actual values.

    import * as pulumi from "@pulumi/pulumi"; import * as aws from "@pulumi/aws"; // Set aws configuration const awsConfig = new aws.config.Provider("aws-config", { accessKey: "<ACCESS_KEY>", secretKey: "<SECRET_ACCESS_KEY>", region: "us-west-2", }); const instance1 = new aws.ec2.Instance("web-server-www1", { ami: "<AMI_ID>", instanceType: "t2.micro", }, { provider: awsConfig }); const instance2 = new aws.ec2.Instance("web-server-www1", { ami: "<AMI_ID>", instanceType: "t2.micro", }, { provider: awsConfig });

    This program would result in an error as you're trying to create two resources with the same name "web-server-www1". In a Pulumi program, each resource name must be distinct.

    If you want to check if a resource already exists before creating it, Pulumi does not support this in the traditional "check if this exists before I create it" usage pattern.

    Pulumi manages this for you -- if the resource is in the stack's state, it is assumed to exist, and if not, Pulumi will create it (if possible). If a resource is in a stack's state and it does not exist in the cloud provider, Pulumi will attempt to create it.

    You can find more information at this link: https://www.pulumi.com/registry/packages/aws/api-docs/ec2/instance/