Document

SUBSCRIBE TO GET FULL ACCESS TO THE E-BOOKS FOR FREE 🎁SUBSCRIBE NOW

Professional Dropdown with Icon

SUBSCRIBE NOW TO GET FREE ACCESS TO EBOOKS

Terraform DataSource

 

 

Terraform Data Sources

Terraform Data Sources are a kind of an API that fetches the data/information from the resources running under the cloud infra and sending it back to terraform configuration for further use.

filter: Although we have created only one instance but still we have used filter because in a production-like environment you might have multiple aws_instance running, so you need to filter the instance anyhow. And since we have tagged our aws_instance with the name Terraform EC2 so we are going to use the same name inside the filter also.

depends_on: The second important parameter is depends_on because data source does not know by its own which resource it belongs to, so we are going to add the depends_on parameter.

image

image

provider “aws” {
  region =“us-east-1”
}

data “aws_ami” “awslinux”{
    most_recent = true
    owners = [“amazon”]
    filter {
      name =“name”
      values =[“amzn2-ami-hvm*”]
    }
    filter {
      name =“root-device-type”
      values = [“ebs”]
    }
    filter {
      name= “virtualization-type”
      values = [“hvm”]
    }
    filter {
      name = “architecture”
      values =[“x86_64”]
    }
}  
resource “aws_instance” “ins1” {
  ami = data.aws_ami.awslinux.id
  instance_type = “t2.micro”
  key_name = “newkey”
 
}

Example to find the public ip of created Instance

provider "aws" {
    region     = "ap-south-1"
   
}
resource “aws_instance” “ins2” {
  ami = “ami-0108d6a82a783b352”
  key_name = var.key
  instance_type = var.instancetype
  count = 2 //interpolation
  tags = {
    “Name” = “Count ${count.index}
  }
}
data “aws_instance” “myawsinstance” {
    filter {
        name = “tag:Name”
        values = [“Count 0”]
    }

    depends_on = [
      aws_instance.ins2
    ]
}

output “fetched_info_from_aws” {
  value = data.aws_instance.myawsinstance.public_ip
}
 

Example to list all Ebs volume

 
provider "aws" {
   region     = "ap-south-1"
   
}

data "aws_ebs_volumes" "ebsvolume" {

  filter {
    name = "volume-type"
    values = [
      "gp2"]
  }
}
output "result" {
value=data.aws_ebs_volumes.ebsvolume.ids
}

Share your love

Leave a Reply

Your email address will not be published. Required fields are marked *