Is there a way to condition on whether something exists in Terraform?
I want to implement the following logic in Terraform: ``` If a IAM policy `foo` exists in the account: Attach to IAM role `bar` as a permissions boundary else: Create IAM role `bar` without permissions boundary ``` Is this possible? --- <ins datetime="2022-07-12T16:22:13Z"> <p><a href="https://support.gruntwork.io/hc/requests/108962">Tracked in ticket #108962</a></p> </ins>
AFAIK, this is not possible in pure Terraform due to the fact that the `aws_iam_policy` data source will error out if there is no IAM Policy that matches the given query. However, there are a few hacks and escape hatches you can rely on to implement something like this: - You can use [the external data source](https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source) with a script to handle the lookup, which will return `true` or `false` depending on if the policy exists. This way, the data source will run to completion regardless of if the resource exists, and give you the information you need to construct the conditional. - If you are using `terragrunt`, you can do something similar in `terragrunt`, with the [run_cmd](https://terragrunt.gruntwork.io/docs/reference/built-in-functions/#run_cmd) function to set a Terraform variable to disable the look up and permissions boundary. - You can either fork the Terraform provider or roll out your own that implements this logic in a custom data source. E.g., something like an `aws_iam_policies` data source that returns a list of IAM policies that match a specific filter. This way, the data source will run to completion even if the IAM policy doesn't exist.