working on typescript , how can i validate if reso...
# getting-started
s
working on typescript , how can i validate if resouces exists before try to create it. ?
c
Within one stack, or within one AWS Account + Region?
s
aws account + region
i want to validate if it's exists
if it's exists just return the ID 🙂
c
You can accomplish this with an exhaustive use of get functions - eg https://www.pulumi.com/registry/packages/aws/api-docs/ec2/getvpc/ but I'd suggest this may not be optimal. For resources where AWS does not enforce uniqueness ( like VPCs ), who cares if there is another with the same name? Within the scope of your stack, that should be irrelevant. If you want to enforce naming standards across an account, you should probably do that via some tag enforcement regiment.
d
Using the
get
functions for this doesn't work well. Consider that the resource doesn't exist, the stack will then create the resource. On subsequent runs, the
get
will find the resource, which will result in the resource getting deleted as you're fetching with
get
instead of with the standard resource object. A common strategy is to use multiple projects if you're in a situation where mulitple stacks depend on a common resource, then use stack references to pass the id around: https://www.pulumi.com/learn/building-with-pulumi/stack-references/
c
@dry-keyboard-94795 yeah you have to combine it with
import
IDs, personally I'd consider it an anti-pattern unless you have some specific import migration task you're trying to accomplish
s
so there is not easy way for it ?
d
Conditional creation, no. But depending on your needs, there are other strategies, such as using
import
to adopt an already existing resource; or stack references where you have common resources across multiple stacks
s
so it will look like this import * as pulumi from "@pulumi/pulumi"; import * as aws from "@pulumi/aws"; // Replace "vpc-abcde1234" with your actual VPC ID const vpcId = "vpc-abcde1234"; const vpc = pulumi.output(aws.ec2.getVpc({ id: vpcId }, { async: true })); let vpcIdVal : string; let publicSubnetIdsVal : string[]; // Extract 'vpcId' and 'publicSubnetIds' from Output<> type via 'apply' method vpc.apply(vpc => { vpcIdVal = vpc.id; // Assume 'publicSubnetIds' are stored as tags in the VPC publicSubnetIdsVal = vpc.tags["publicSubnetIds"].split(","); console.log(
VPC ID: ${vpcIdVal}
); console.log(
Public Subnet IDs: ${publicSubnetIdsVal}
); });
d
The
.apply
doesn't necessarily run until the end of the stack, so the values will likely not be set. Most resources will accept
Output
as parameters, so can use
vpc.id
directly
s
can you help with small code example 🙂
d
const vpcIdVal: Output<string> = vpc.id
Like this
const publicSubnetIds: Output<string[]> = vpc.apply(v => v.tags["publicSubnetIds"].split(","))
Then apply can be used to extract individual values as well, though I think there's a dedicated function for querying subnetIDs based on the vpc