如何创建通用的弹性 beanstalk 模块?

How can I create a generic elastic beanstalk module?

我正在尝试为弹性 beantalk 资源创建一个可重用的 terraform 模块。我一直在试图弄清楚如何传递应用程序环境变量。我想做这样的事情:

./api.tf

module "eb" {
  source = "./eb"

  name    = "api"
  vpc_id  = "${var.vpc_id}"
  ...

  environment = {
    VAR1  = "${var.var1}"
    VAR2  = "${var.var2}"
    VAR3  = "${var.var3}"
    ...
  }  
}

./eb/eb.tf

variable "name"         { }
variable "vpc_id"       { }
variable "environment"  { type = "map" }

resource "aws_elastic_beanstalk_environment" "api" {
  name  = "${var.name}"
  ...

  setting {
    namespace   = "aws:ec2:vpc"
    name        = "VPCId"
    value       = "${var.vpc_id}"
  }

  # application environment variables

  # Here's where I'm stuck:
  # I would like to iterate over the environment map, setting name and value.
  setting {
    count       = "${length(keys(var.environment))}"
    namespace   = "aws:elasticbeanstalk:application:environment"
    name        = "${element(keys(var.environment), count.index)}"
    value       = "${lookup(var.environment, element(keys(var.environment), count.index))}"
  }
}

我的第一个问题是选项似乎不支持计数。有没有其他方法可以完成类似的事情,以便我可以为 eb 模块提供额外的设置?

我根据这个答案找到了解决方案:https://github.com/hashicorp/terraform/issues/12294#issuecomment-323235796

您可以在 Terraform 中使用 "list" 类型的变量来指定地图列表。

这对我有用:

provider aws {
  region = "us-east-1"
}

variable environment_variables {
  type = "list"
  default = [
    {
      namespace = "aws:elasticbeanstalk:application:environment"
      name = "VAR1"
      value = "Value1"
    },
    {
      namespace = "aws:elasticbeanstalk:application:environment"
      name = "VAR2"
      value = "Value2"
    }
  ]
}

resource "aws_elastic_beanstalk_application" "app" {
  name = "temp-example-app"
}

resource "aws_elastic_beanstalk_environment" "app" {
  name = "temp-example-app"
  application = "${aws_elastic_beanstalk_application.app.id}"
  solution_stack_name = "64bit Amazon Linux 2017.03 v2.6.0 running Docker 1.12.6"

  setting = ["${var.environment_variables}"]

  setting {
    namespace = "aws:autoscaling:launchconfiguration"
    name = "InstanceType"
    value = "t2.micro"
  }
  setting {
    namespace = "aws:elasticbeanstalk:environment"
    name = "EnvironmentType"
    value = "SingleInstance"
  }
}

注意:我没有指定应用程序版本,因此您在应用时可能会遇到错误,但您应该能够在 AWS 控制台中看到环境变量。