Could someone please give me an example of how to programmatically create Terraform provider aliases based on a variable map? This is what I've tried, but I'm receiving the following error:
variable "aws_regions" {
default = [
{
region = "us-east-1"
alias = "default"
},
{
region = "us-east-2"
alias = "useast2"
},
{
region = "us-west-1"
alias = "uswest1"
},
{
region = "us-west-2"
alias = "uswest2"
},
{
region = "eu-central-1"
alias = "eucent1"
}
]
}
provider "aws" {
count = "${length(var.aws_regions)}"
region = "${lookup(var.aws_regions[count.index], "region")}"
alias = "${lookup(var.aws_regions[count.index], "alias")}"
}
# CloudWatch Log Groups
resource "aws_cloudwatch_log_group" "linux" {
count = "${length(var.aws_regions)}"
provider = "aws.${lookup(var.aws_regions[count.index], "alias")}"
name = "Linux"
}
Error:
$ terraform plan
* provider.aws.${lookup(var.aws_regions[count.index], "alias")}: count.index: count.index is only valid within resources
It turns out that Terraform provider processing takes place very early and the current version (v.0.11.3) doesn't currently support variable interpolation for providers. I did discover a workaround that isn't too terrible, but it requires a lot of code duplication.
main.tf
# Default Region
provider "aws" {
region = "us-east-1"
version = "~> 1.8"
}
provider "aws" {
alias = "us-east-1"
region = "us-east-1"
}
provider "aws" {
alias = "us-east-2"
region = "us-east-2"
}
provider "aws" {
alias = "us-west-1"
region = "us-west-1"
}
provider "aws" {
alias = "us-west-2"
region = "us-west-2"
}
provider "aws" {
alias = "eu-central-1"
region = "eu-central-1"
}
# CloudTrail Setup in Default Region
module "cloudtrail" {
source = "./cloudtrail"
}
# CloudWatch Setup per Region
module "us-east-1_cloudwatch" {
source = "./cloudwatch"
providers = {
"aws.region" = "aws.us-east-1"
}
}
module "us-east-2_cloudwatch" {
source = "./cloudwatch"
providers = {
"aws.region" = "aws.us-east-2"
}
}
module "us-west-1_cloudwatch" {
source = "./cloudwatch"
providers = {
"aws.region" = "aws.us-west-1"
}
}
module "us-west-2_cloudwatch" {
source = "./cloudwatch"
providers = {
"aws.region" = "aws.us-west-2"
}
}
module "eu-central-1_cloudwatch" {
source = "./cloudwatch"
providers = {
"aws.region" = "aws.eu-central-1"
}
}
cloudwatch/main.tf
provider "aws" {
alias = "region"
}
# CloudWatch Log Groups
resource "aws_cloudwatch_log_group" "linux" {
name = "Linux"
provider = "aws.region"
tags {
OS = "Linux"
}
}
Use workspaces - it can be used for replicable use cases such as dev environments and multi-regions. https://www.terraform.io/docs/state/workspaces.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.