There are some data sources that give some important information about underlying infrastructure like which region/zone we are working on aws.
data keyword is used to depict data sources
provider "aws" {}
data "aws_region" "current" {}
output "region_name" {
value = data.aws_region.current.name
}
output "region_description" {
value = data.aws_region.current.description
}
Get aws account id, arn, user_id
provider "aws" {}
data "aws_caller_identity" "current" {}
output "account_id" {
value = data.aws_caller_identity.current.account_id
}
output "caller_arn" {
value = data.aws_caller_identity.current.arn
}
output "user_id" {
value = data.aws_caller_identity.current.user_id
}
Print all vpc’s id
data "aws_vpcs" "vpcs" {}
output "all_vpc_ids" {
value = data.aws_vpcs.vpcs.ids
}
Vpc’s with SANDBOX tag name
data "aws_vpc" "sandbox" {
tags = {
Name = "SANDBOX"
}
}
Create subnet with availability zones and sandbox vpc id
data "aws_availability_zones" "working" {}
data "aws_vpc" "sandbox" {
tags = {
Name = "SANDBOX"
}
}
resource "aws_subnet" "subnet1" {
vpc_id = data.aws_vpc.sandbox.id
availability_zone = data.aws_availability_zones.working.names[0]
cidr_block = "10.0.1.0/24"
tags = {
Name = "Subnet-1"
Info = "AZ: ${data.aws_availability_zones.working.names[0]} in Region: ${data.aws_region.current.description}"
}
}
resource "aws_subnet" "subnet2" {
vpc_id = data.aws_vpc.sandbox.id
availability_zone = data.aws_availability_zones.working.names[1]
cidr_block = "10.0.2.0/24"
tags = {
Name = "Subnet-2"
Info = "AZ: ${data.aws_availability_zones.working.names[1]} in Region: ${data.aws_region.current.description}"
}
}