'How to get the data source for an AWS CloudFront Origin Access Identity in Terraform
We have terraform code in another project that must remain in that separate project that creates three AWS CloudFront Origin Access Identities - one that we want to use for all of our qa environments, one for all of our pprd environments, and one for all of our prod environments.
In another project, how can I use Terraform to get the datasource for these to use them in creating a CloudFront distribution with Terraform?
Does the datasource have to use the OAI ID or name to filter on and how? What happens if the OAI changes. I guess what I am getting at is I would prefer to avoid hard coding the ID or name if possible - Or is that the only way to do this?
We have three OAI's that we will need to use separately - In other words, we will be creating multiple qa distributions that will use the qa OAI, multiple pprd distributions that will use the pprd OAI, and multiple prod distributions that will use the prod OAI.
Let's assume that the ID's are AAAAAAA for the qa one, BBBBBBBB for the pprd one, and CCCCCCC for the prod one (blurred out the real ones in case there is a security issue in posting them).
Solution 1:[1]
Yes, you can get the Origin Access Identity created by another stack. In fact there are multiple ways to get it.
The easiest way would be to use a aws_cloudfront_origin_access_identity data source. You can define a data source as follows:
data "aws_cloudfront_origin_access_identity" "example" {
id = "EDFDVBD632BHDS5"
}
The id is the identifier of the distribution. For the attribute references of the data block, you would want to check out the docs.
What happens if the OAI changes?
The data block assumes that the resource already exists in AWS and was created outside of the current state. This means that it will be refreshed every time you do a terraform plan. If something changes on the resource, it will be detected at the next plan.
I guess what I am getting at is I would prefer to avoid hard coding the ID or name if possible.
In case of a data block, you have to provide the ID somehow. This can be either using a variable or hard-coding it. Now, if you really want to avoid this, you can use another method for importing remote resources.
The other option would be to read from a Terraform remote state by having a terraform_remote_state data source. This option is a bit more complex, since the remote state has to expose attributes as outputs. Also, you have to provide the location of the remote state, so can also be considered a hardcoded value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ervin Szilagyi |

