How are data sources used in Terraform?

user389955 picture user389955 · Dec 8, 2017 · Viewed 26.6k times · Source

The Terraform Data Sources documentation tells me what a data source is, but I do not quite understand it. Can somebody give me a use case of data source? What is the difference between it and configuring something using variables?

Answer

TJ Biddle picture TJ Biddle · Dec 8, 2017

Data sources can be used for a number of reasons; but their goal is to do something and then give you data.

Let's take the example from their documentation:

# 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
}

This uses the aws_ami data source - this is different than a resource! It will instead just give you information, and not create anything. This example in particular will call out to the describe-images AWS API call, pass in a few --filter options as specified, and return an object that you can get information from - take a look at these attributes!

  • name
  • owner_id
  • description
  • image_id

... The list goes on. This is really useful if I were, let's say - always wanting to pull the latest AMI matching some tags, and keep a launch configuration up to date with it. I could use this data provider rather than always have to update a variable or hard-code the ID.

Data source can be used for other reasons as well; one of my favorites is the template provider.

Good luck!