Tha*_*yne 7 terraform terraform-provider-aws
我有一个模块,我想在另一个区域有条件地创建 s3 存储桶。我尝试过这样的事情:
resource "aws_s3_bucket" "backup" {
count = local.has_backup ? 1 : 0
provider = "aws.backup"
bucket = "${var.bucket_name}-backup"
versioning {
enabled = true
}
}
Run Code Online (Sandbox Code Playgroud)
但即使 count 为 0,我似乎也需要提供 aws.backup 提供程序。有什么办法解决这个问题吗?
注意:如果我可以使用单个提供程序在多个区域创建存储桶,这不会成为问题,请参阅https://github.com/terraform-providers/terraform-provider-aws/issues/8853
根据您的描述,我了解到您希望使用相同的“配置文件”但在不同的区域创建资源。对于这种情况,我会采取以下方法:
为您创建一个模块文件 s3_bucket_backup,在该文件中您将使用变量构建“备份提供程序”。
# Module file for s3_bucket_backup
provider "aws" {
region = var.region
profile = var.profile
alias = "backup"
}
variable "profile" {
type = string
description = "AWS profile"
}
variable "region" {
type = string
description = "AWS profile"
}
variable "has_backup" {
type = bool
description = "AWS profile"
}
variable "bucket_name" {
type = string
description = "VPC name"
}
resource "aws_s3_bucket" "backup" {
count = var.has_backup ? 1 : 0
provider = aws.backup
bucket = "${var.bucket_name}-backup"
}
Run Code Online (Sandbox Code Playgroud)
在您的主 tf 文件中,使用局部变量声明您的提供商配置文件,调用传递配置文件和不同区域的模块
# Main tf file
provider "aws" {
region = "us-east-1"
profile = local.profile
}
locals {
profile = "default"
has_backup = false
}
module "s3_backup" {
source = "./module"
profile = local.profile
region = "us-east-2"
has_backup = true
bucket_name = "my-bucket-name"
}
Run Code Online (Sandbox Code Playgroud)
现在您已经完成了,您现在可以使用不同区域的相同“配置文件”来构建 s3_bucket_backup。
在上面的例子中,主文件使用的区域是 us-east-1,桶创建在 us-east-2 上。
如果将 has_backup 设置为 false,则不会创建任何内容。
由于“备份提供程序”是在模块内部构建的,因此您的代码不会因为主 tf 文件中包含多个提供程序而显得“脏”。
归档时间: |
|
查看次数: |
2412 次 |
最近记录: |