我的main.tf文件中包含以下代码:
provider "aws" {
access_key = "${var.aws_access_key}"
secret_key = "${var.aws_secret_key}"
region = "us-east-1"
alias = "us-east-1"
}
provider "aws" {
access_key = "${var.aws_access_key}"
secret_key = "${var.aws_secret_key}"
region = "us-west-1"
alias = "us-west-1"
}
module "us-east_vpc" {
source = "./setup-networking"
providers = {
"aws.region" = "aws.us-east-1"
}
}
module "us-west_vpc" {
source = "./setup-networking"
providers = {
"aws.region" = "aws.us-west-1"
}
}
然后在我的模块文件中:
provider "aws" {
alias = "region"
}
resource "aws_vpc" "default" {
provider = "aws.region"
cidr_block = "${lookup(var.vpc_cidr, ${aws.region.region})}"
enable_dns_hostnames = true
tags {
Name = "AWS VPC"
}
}
resource "aws_internet_gateway" "default" {
provider = "aws.region"
vpc_id = "${aws_vpc.default.id}"
}
resource "aws_subnet" "default" {
provider = "aws.region"
vpc_id = "${aws_vpc.default.id}"
cidr_block = "${lookup(var.subnet_cidr, ${aws.region.region})}"
availability_zone = "aws.region"
tags {
Name = "AWS Subnet"
}
}
resource "aws_route_table" "default" {
provider = "aws.region"
vpc_id = "${aws_vpc.default.id}"
route {
cidr_block = "0.0.0.0/0"
gateway_id = "${aws_internet_gateway.default.id}"
}
tags {
Name = "Main Gateway"
}
}
正如您在模块文件代码中看到的那样,我正在尝试查找以从映射变量中查找VPC CIDR掩码和子网CIDR掩码。
问题是我似乎无法弄清楚如何获取要用作查询值的区域。
如果我对这些值进行硬编码:
cidr_block = "10.10.0.0/16"
cidr_block = "10.10.10.0/24"
脚本按预期工作,但我不想对值进行硬编码。
具有更多Terraform经验的人可以帮助我理解如何正确引用该区域以查找正确的值吗?
答案 0 :(得分:1)
您可以使用aws_region
data source获取提供者当前正在使用的区域。
因此,在您的情况下,您可以执行以下操作:
provider "aws" {
alias = "region"
}
data "aws_region" "current" {
provider = "aws.region"
}
resource "aws_vpc" "default" {
provider = "aws.region"
cidr_block = "${lookup(var.vpc_cidr, ${data.aws_region.current.name})}"
enable_dns_hostnames = true
tags {
Name = "AWS VPC"
}
}
...
答案 1 :(得分:0)
provider "aws" {
alias = "region"
}
data "aws_region" "current" {
provider = "aws.region"
}
data "aws_availability_zone" "current" {
provider = "aws.region"
name = "${data.aws_region.current.name}a"
}
resource "aws_vpc" "default" {
provider = "aws.region"
cidr_block = "${lookup(var.vpc_cidr, data.aws_availability_zone.current.name)}"
enable_dns_hostnames = true
tags {
Name = "${data.aws_region.current.name} Security VPC1"
Region = "${data.aws_region.current.name}"
Account = "Security"
}
}
答案 2 :(得分:0)
我一直在寻找相同的答案来解决其他问题。我想获得一个角色名称的区域,我可以通过以下方式获取信息:
1.-创建一个类似data.tf
的文件并添加以下信息:
data "aws_region" "current" {}
2.-通过在任何TF文件中调用此变量从数据中获取信息:
name = "${var.vpc-name}-${data.aws_region.current.name}-Bastion-Role"
这样,它将获得您正在执行代码的区域,并且您不必弄乱provider.tf
文件。