Alias and Data sources in Terraform
Alias and Data sources in Terraform
Alias:
What if I need to launch my resources in multiple regions within a single configuration file then Alias variable does this functionality.
In the below example we have declared
alias = “pillows” in one provider block.
we can call this variable to refer to a resource other than a default region with the following syntax
provider = providername. aliasvariablename
In our case alias variable is “pillows” and provider is aws so therefore we can write it as provider =pillows.aws
Provider”aws” {
region = “us-east-1”
access_key = “
}
provider “aws” {
region = “ap-south-1”
access_key = “
alias = “pillows”
}
resource aws_instance “myec2” {
ami = “ami-96fda3c22c1c990a”
instance_type = “t2.small”
tags = {
name = “devservers”
}
}
resource aws_instance “myec3” {
ami = “ami-08f63db601b82ff5f”
instance_type = “t2.medium”
provider = aws.pillows
tags = {
name = “prodservers”
}
}
Data sources :
Data sources allow data to be fetched or computed for use elsewhere in Terraform configuration. Use of data sources allows a Terraform configuration to make use of information defined outside of Terraform, or defined by another separate Terraform configuration.
Syntax for Data source:
The syntax for data source starts with keyword Data fallowed by data source name.
Data “datasourcename” “nayname”
Example:
In the below example we are fetching ami id dynamically using aws_ami data source.
under the code if we need to call the ami the syntax is :
ami = data.datsourcename.resourcename.attributename
in our example it is ami = data.aws_ami.myec2.id
provider “aws” {
access_key = “”
secret_key = “qZY “
region = “us-east-1”
}
data “aws_ami” “myec2” {
most_recent = true
owners = [“amazon”]
filter {
values = [“redhat8-ami-hvm*”]
name = “name”
}
}
resource “aws_instance” “myec2” {
ami = data.aws_ami.myec2.id
instance_type = “t2.large”
}