【问题标题】:Is it possible to have conditional arguments in terraform resourcesterraform 资源中是否可以有条件参数
【发布时间】:2021-12-22 05:21:06
【问题描述】:

我正在尝试使用时间表在 AWS 中设置数据同步,但是我只需要 2 个环境中的时间表,有没有办法可以设置条件参数,以便仅在开发和测试中设置时间表。

resource "aws_datasync_task" "data-load" {
  destination_location_arn = aws_datasync_location_s3.destination.arn
  name                     = "data-load"
  source_location_arn      = aws_datasync_location_nfs.source.arn

  schedule {
    schedule_expression = "cron(0 12 ? * SUN,WED *)"
  }
}

我试过了

  schedule {
    schedule_expression = var.data_sync_schedule
  }


variables.tf:

variable "data_sync_schedule" {
  default = null
}

dev and test tfvars:

data_sync_schedule = "cron(0 8 * * ? *)"

但对于除开发测试以外的所有其他环境,我收到以下错误:

╷
│ Error: Missing required argument
│ 
│   with aws_datasync_task.data-load[0],
│   on data-sync.tf line 19, in resource "aws_datasync_task" "data-load":
│   19:     schedule_expression = var.data_sync_schedule
│ 
│ The argument "schedule.0.schedule_expression" is required, but no
│ definition was found.

任何建议将不胜感激。

【问题讨论】:

    标签: terraform terraform-provider-aws


    【解决方案1】:

    您需要将整个aws_datasync_task 资源设置为有条件的,而不是尝试使调度表达式为空。您可以使用资源上的 count 参数来做到这一点,将其设置为 01

    【讨论】:

    【解决方案2】:

    您可以执行以下操作:

    resource "aws_datasync_task" "data-load" {
      destination_location_arn = aws_datasync_location_s3.destination.arn
      name                     = "data-load"
      source_location_arn      = aws_datasync_location_nfs.source.arn
    
      schedule {
        schedule_expression = var.env == 'dev' ? "cron(0 12 ? * SUN,WED *)" : null
      }
    }
    

    Var.env 将通过您的 CI/CD 作业设置

    【讨论】:

      猜你喜欢
      • 2022-08-02
      • 2018-01-21
      • 1970-01-01
      • 2019-08-04
      • 2021-08-07
      • 2019-10-20
      • 2019-07-17
      • 1970-01-01
      • 2011-06-04
      相关资源
      最近更新 更多