terraform

How are data sources used in Terraform?


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?


Solution

  • 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!

    ... 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!