Terraform check if resource exists before creating it

In Terraform, is there a way to check if a resource already exists before attempting to create it?

In my CI/CD pipeline, I need to check for the existence of certain resources during a job, using terminal commands, bash, or an API. If the resources exist, I want to use them; otherwise, I want to create them. My goal is to create necessary infrastructure resources on demand, but avoid Terraform errors in my CI/CD builds if the resources already exist.

Normally, Terraform doesn’t think about / consider anything that’s not in its state.

If the issue is that you’re not storing state between runs, or lack of cleanup on failure, I’d suggest using a remote state for your CI runs, and making sure you configure a cleanup / destroy step that executes even in the case of a failed run.

If the issue is that things outside of Terraform might have created a given resource, you’d have to do some sort of workaround.

One option would be to do something like terraform import xyz foo.the_resource || true before running your plan / apply.

Usually you can use the data resource to retrieve a value from any resource created, but validate if the resource exists I don’t know if the data source can do that, you should try to test it.

Typically, if the resource was created manually, and you’re now wanting terraform to take over management, you’d use terraform import or the import {} block.

Ooh, yeah, forgot about import {} blocks, but that’s a good idea.