地形查找AWS区域 [英] Terraform lookup AWS region
问题描述
我的main.tf文件中包含以下代码:
I have the following code in my main.tf file:
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"
}
}
然后在我的模块文件中:
And then in my modules file I have:
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掩码.
As you can see in the modules file code I am trying to do a lookup to find the VPC CIDR mask and the subnet CIDR mask from map variables.
麻烦的是,我似乎无法弄清楚如何获取要用作查询值的区域.
The trouble is that I can't seem to sort out how to get the region to be used as a lookup value.
如果我对这些值进行硬编码:
If I hard code these values:
cidr_block = "10.10.0.0/16"
cidr_block = "10.10.10.0/24"
脚本按预期工作,但是我不想对值进行硬编码.
The script works as expected but I don't want to hard code the values.
具有更多Terraform经验的人可以帮助我理解如何正确引用该区域以查找正确的值吗?
Can someone with more Terraform experience help me understand how I can properly reference the region to lookup the correct value?
推荐答案
You can get the region that's currently in use by the provider by using the aws_region
data source.
因此,在您的情况下,您可以执行以下操作:
So in your case you could do something like this:
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"
}
}
...
这篇关于地形查找AWS区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!