Terraform: Data Sources

data source lets data be fetched or computed and used elsewhere in Terraform’s configuration.

Note: every data source is mapped to a provider based on the longest prefix matching. E.g. aws_ami data source would map to the aws provider.

Using the example Terraform provide here:

https://www.terraform.io/docs/configuration/data-sources.html

i.e.

(the code inside the top {} is the Configuration block)

and a resource that uses this data source:

(the code inside the top {} is the Attributes block).

The ami it will use will be the value (i.e. the id) returned by our data source. i.e. data.aws_ami.web.id

Our data source finds this by doing a query on the provider awsfor aws_ami (see https://www.terraform.io/docs/providers/aws/d/ami.html ) and filtering on state, the Componenttag and most recent.

Configuration block

Note that the configuration depends on the data source as specified in the providersdocs on Terraform. See Argument Reference for that data source. E.g. for aws_amiit would be:

Argument Reference: https://www.terraform.io/docs/providers/aws/d/ami.html#argument-reference

(i.e. filter, most_recent).

Attributes block

To reference attributes of the data source you access attributes.

i.e. data.aws_ami.web.id

https://www.terraform.io/docs/providers/aws/d/ami.html#attributes-reference

Meta parameters

Data sources are basically a read-only subset of resources so support the same meta-parameters as resources. The only exception being that, as they’re read-only, they don’t support the lifecycle configuration block.

Meta-parameters: e.g. count, depends_on, provider

Lifecycle configuration block: e.g. create_before_destroy

Data Source Lifecycle

If data instance refers to resources that haven’t been created then these values won’t be available till the apply phase and will show computed in the plan.

If it refers to already existing resources then they will show up in the refresh (prior to plan) and therefore plan phases.

Leave a Reply

Your email address will not be published. Required fields are marked *