Data Sources
Data sources allow Terraform to use information defined outside of Terraform, defined by another separate Terraform configuration, or modified by functions.
Using Data Sources
1 2 3 4 5 6 7 8 9 |
|
A data block requests that Terraform read from a given data source (aws_ami
) and export the result under the given local name (example
). The name is used to refer to this resource from elsewhere in the same Terraform module, but has no significance outside of the scope of a module.
The data source and name together serve as an identifier for a given resource and so must be unique within a module.
Within the block body (between {
and }
) are query constraints defined by the data source. Most arguments in this section depend on the data source, and indeed in this example most_recent
, owners
and tags
are all arguments defined specifically for the aws_ami
data source.
Examples
Using data sources to access external resource attributes
1 2 3 |
|
I have a bucket named sumeet.life
in my AWS account.
When this Terraform configuration with appropriate provider settings is initialized and enabled, Terraform reads the information from AWS and makes it available in the data.aws_s3_bucket.existing_bucket
variable.
Managing resource dependencies with data sources
Data sources indirectly help manage resource dependencies. If the data being queried by data sources does not exist, then the resource that is dependent on the same will not be created.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Validate inputs with data sources
1 2 3 4 5 6 7 8 9 10 11 |
|
If we provide invalid instance_ami
the terraform output does not throw any error
1 2 3 4 5 6 7 8 9 10 |
|
However, it does throw an error when we proceed to apply this configuration since the given AMI does not exist.
In certain scenarios, it might be desirable for this configuration to throw an error in the planning phase itself for various reasons. This is achieved using data sources.
1 2 3 4 5 6 7 |
|
If we provide invalid instance_ami
the terraform plan output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Using data sources to access AWS secrets
Secrets Manager is a service provided by AWS to manage sensitive data. It stores the sensitive variables securely using encryption, and makes them available to various services for automation purposes.
In Terraform configurations, these secrets are accessed using data sources.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|