【问题标题】:How do I use s3 lifeycle rules in Terraform in a modular form, i.e. referenced in separate JSON?如何以模块化形式在 Terraform 中使用 s3 生命周期规则,即在单独的 JSON 中引用?
【发布时间】:2021-02-08 04:48:17
【问题描述】:

目前,我在我的 s3 资源下指定了生命周期规则:

resource "aws_s3_bucket" "bucket-name" {
  bucket = "bucket-name"
  
  lifecycle_rule {
    id = "Expiration Rule"
    enabled = true
    prefix = "reports/"

  expiration {
    days = 30
    }
  }
}

...但我想必须有一种方法可以使这更加模块化,例如将生命周期规则放入单独的 JSON 中,以便我可以为多个 s3 存储桶引用它并减少编辑每个资源的需要。我通常知道如何做到这一点,并且已经使用其他资源做到了这一点,如下所示:

resource "aws_iam_policy" "devops-admin-write" {
  name = "devops-admin-s3"
  description = "Devops-Admin group s3 policy."
  policy = file("iam_policies/devops-admin-write.json")
}

...不同之处在于“lifecycle_rule”是一个参数而不是一个属性 - 我不清楚如何使它工作。 Google-Fu 也没有给出明确的答案。

【问题讨论】:

    标签: json amazon-web-services amazon-s3 terraform terraform-provider-aws


    【解决方案1】:

    您可以使用通过通用local 变量执行的dynamic blocks。 因此,您只需要更改局部变量,更改将反映在使用此变量的所有地方。

    为了使其更易于维护,我建议构建一个模块并重用该模块或使用现有模块。

    locals + dynamic 的实现可能如下所示:

    locals {
      lifecycle_rules = [
        {
          id      = "Expiration Rule"
          enabled = true
          prefix  = "reports/"
          expiration = {
            days = 30
          }
        }
      ]
    }
    
    resource "aws_s3_bucket" "bucket-name" {
      bucket = "bucket-name"
      
      dynamic "lifecycle_rule" {
        for_each = local.lifecycle_rules
       
        content {
          id      = lifecycle_rule.each.id
          enabled = lifecycle_rule.each.enabled
          prefix  = lifecycle_rule.each.prefix
    
          expiration {
            days = lifecycle_rule.each.expiration.days
          }
        }
      }
    }
    

    这不会检查错误,当然也不完整 - 它只是实现您的示例。

    our terraform s3-bucket module 中查看更完整的通用示例:find code here

    【讨论】:

      猜你喜欢
      • 2020-01-02
      • 2019-08-17
      • 2021-12-13
      • 2021-02-07
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      相关资源
      最近更新 更多