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:



# Find the latest available AMI that is tagged with Component = web
data "aws_ami" "web" {
  filter {
    name   = "state"
    values = ["available"]

  filter {
    name   = "tag:Component"
    values = ["web"]

  most_recent = true

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

and a resource that uses this data source:

resource "aws_instance" "web" {
  ami           = "${data.aws_ami.web.id}"
  instance_type = "t1.micro"

(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


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 *