How to use Data Source in Terraform

This post explains how to use Data Sources in Terraform.To follow steps described in this article you need have below prerequisites configured.

Prerequisites

  • Terraform Installation
  • AWS CLI Installation
  • AWS Credentials Configuration

Follow Set up Terraform with AWS from scratch if you don't have these prerequisites configured.

Terraform Data Sources

Data sources in Terraform are used to fetch information from cloud provider APIs, such as disk image IDs, or information about the rest of your infrastructure through the outputs of other Terraform configurations. You can use this information to make your project's configuration more flexible. Let's understand use of data sources with below example.

Provision EC2 without using data sources

Have a look to the below configuration in main.tf where an EC2 instance is getting provisioned and ami id is hard coded in the resource block.

   
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }

  required_version = ">= 0.14.9"
}

provider "aws" {
  profile = "default"
  region  = "us-east-1"
}

resource "aws_instance" "test_instance" {
  ami           = "ami-033b95fb8079dc481"
  instance_type = "t2.micro"

  tags = {
    Name = "test instance"
  }
}    
   

Provision EC2 using data sources

In the above configuration we provided the ami id in the resource block, instead of hard coding ami id in the resource block let't use data sources to look up latest Ubuntu Server 20.04 ami id and use it to provision EC2 instance.

1. Add below configuration to main.tf

   
data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"]
}  
 

2. Update resource block of main.tf as shown below.

   
resource "aws_instance" "my_instance" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"

  tags = {
    Name = "Test Instance"
  }
}
 

3. After updates main.tf should look like as shown below.

   
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }

  required_version = ">= 0.14.9"
}

provider "aws" {
  profile = "default"
  region  = "us-east-1"
}


data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"]
}


resource "aws_instance" "my_instance" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"

  tags = {
    Name = "Test Instance"
  }
} 

 

Run commands terraform fmt, terraform validate and finally terraform apply, respond to the prompt with yes to apply changes.

   
terraform apply
 

Category: AWS