首页 > 解决方案 > 如何限制模块/服务在 terraform 中执行

问题描述

我有多个使用 terraform 配置的环境。我的问题是如何限制特定模块在特定环境中执行。

例如:我只需要在生产环境中部署实例服务和相关模块,而不需要在较低的环境中部署

我有以下带有服务的结构,每个服务调用模块。

结构体:


├── instances
│   ├── config.tfplan
│   ├── data.tf
│   ├── main.tf
│   └── variables.tf
├── modules
│   ├── buckets
│   │   ├── buckets.tf
│   │   ├── outputs.tf
│   │   └── variables.tf
│   ├── compartments
│   │   ├── compartments.tf
│   │   ├── output.tf
│   │   └── variables.tf
│   ├── iam
│   │   ├── groups.tf
│   │   ├── outputs.tf
│   │   ├── policies.tf
│   │   ├── users.tf
│   │   └── variables.tf
│   ├── instances
│   │   ├── instance.tf
│   │   ├── output.tf
│   │   └── variables.tf

在此处输入图像描述

标签: terraform

解决方案


这在旧版本的 Terraform 中是不可能的,但在 0.12.6 版本中是不可能的。您可以for_each在模块中添加。请在此处找到我如何使用的示例for_each

定义变量:

variable "cloudwatch_event" {
  description = "Map of cloudwatch event configuration"
  type        = map(any)
  default = {
    default = {}
  }
}

定义资源:

module "cloudwatch_event" {
  source = "git::git@github.com:tomarv2/terraform-aws-cloudwatch-event.git?ref=v0.0.4"

  for_each = var.cloudwatch_event

  description  = lookup(each.value, "description", null)
  custom_input = lookup(each.value, "custom_input", null)
  suffix       = lookup(each.value, "suffix", "rule")
  schedule     = lookup(each.value, "schedule", null)

  deploy_event_rule   = var.deploy_cloudwatch_event_trigger
  deploy_event_target = var.deploy_cloudwatch_event_trigger

  target_arn = join("", aws_lambda_function.lambda.*.arn)
  #-----------------------------------------------
  # Note: Do not change teamid and prjid once set.
  teamid = var.teamid
  prjid  = var.prjid
}

如您所见,如果没有cloudwatch_event此资源将不会被部署。

请检查位于此处的模块存储库:https ://github.com/tomarv2/terraform-aws-lambda

Terraform 文档供您参考:https ://www.terraform.io/docs/language/meta-arguments/for_each.html


推荐阅读