【问题标题】:use different bucket for terraform s3 backend depending on which aws account is configured根据配置的 aws 帐户,为 terraform s3 后端使用不同的存储桶
【发布时间】:2021-06-07 06:17:57
【问题描述】:

我需要 terraform s3 后端为我的生产 AWS 账户使用一个存储桶,为我的开发 AWS 账户使用另一个存储桶。我们需要这个,因为我们不能允许开发 AWS 账户中的用户访问生产 AWS 账户中的 s3 存储桶。 S3 存储桶名称必须全局唯一,因此存储桶名称字段不能相同。

我尝试在此处使用变量,但在 terraform 后端出现变量错误。这是一个非常需要的功能,有a GitHub issue for it,但它已经开放 4 年了,似乎没有任何计划添加这个功能,所以我需要一个解决方法。一个建议来自同一个 GitHub 问题。该建议是使用terraform remote state data source。不幸的是,这似乎不起作用。这是我尝试过的:

// backend.tf

terraform {
  backend "s3" {}
}
data terraform_remote_state "state" {
  backend = "s3"
  config {
    bucket = var.aws_account == "123456789000" ? "my-prod-bucket" : "my-dev-bucket"
    key    = "apps/main-stack.tfstate"
    region = "us-east-1"
  }
}

没有使用任何值,并提示手动输入所有值。

$ terraform init
Initializing modules...

Initializing the backend...
bucket
The name of the S3 bucket

Enter a value:

我四处寻找其他解决方案,但到目前为止,没有运气。有谁知道如何解决这个问题?

【问题讨论】:

  • @ChinHuang 很好的答案。那里肯定有重叠。我更新了我的问题,以更多地关注实现 aws 帐户到 s3 存储桶奇偶校验的具体问题,并链接到您对后端变量更一般情况的回答。

标签: amazon-s3 terraform terraform-provider-aws terraform0.12+


【解决方案1】:

似乎解决方案是使用后端配置文件。这称为partial configuration。您可以为需要单独后端的每个 aws 帐户保留一个 tfvars 文件,并在初始化 terraform 时提供它,如下所示:

// prod-backend-config.tfvars

bucket = "my-prod-s3-bucket-for-terraform"
// dev-backend-config.tfvars

bucket = "my-dev-s3-bucket-for-terraform"
// backend.tf

terraform {
  backend "s3" {
    // do not set a bucket name here
    key    = "apps/main-stack.tfstate"
    region = "us-east-1"
  }
}
$ terraform init -backend-config prod-backend-config.tfvars

这使您可以在 aws 帐户和后端的 s3 存储桶之间保持对等性。

有关使用任意变量配置任何后端的更通用解决方案,请参阅How to pass variables for Terraform S3 Backend resource?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 2018-10-31
    • 2016-03-02
    • 2017-09-21
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多