Data Sources

Data sources are used to fetch data and to use in Terraform configuration.

The data block creates a data instance of the given TYPE (first parameter) and NAME (second parameter).

The combination of the type and name must be unique.

Generally, we use data sources to fetch list of amis, availability zones for a specified region in AWS.

Let’s create variables for region and its availability zones.

variable "region" {
  default "us-east-1"
}
variable "azs" {
  type ="list"
  default =["us-east-1a",us-east-1b","us-east-1c"]
}

In the above configuration, availability zones are hard coded. If we change the region, we have to change the availability zones as well.

To avoid this, we can use data sources to fetch availability zones for a specified region using “aws_availability_zones” as bellow.

variable "region" {
  default "us-east-1"
}

data "aws_availability_zones" "azs" {}

Another example :

Fetch latest available AMI that is tagged with Component = web.

data "aws_ami" "web" {
  most_recent = true
  filter {
    name = "state"
    values = ["available"]
  }
  filter {
    name = "tag:Component"
   values = ["web"]
  }
}

Here, most_recent is specified to return one result (latest) if more AMIs available. filter argument is used to filter the AMIs for specified condition.

Usage

Each data instance will export one or more attributes, which can be insert into other resources using variables of the form “data.TYPE.NAME.ATTRIBUTE“.

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