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

时间:2017-01-27 02:32:19

标签: terraform

我正在尝试为弹性beanstalk资源创建可重用的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模块提供其他设置?

1 个答案:

答案 0 :(得分:4)

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

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

这对我有用:

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控制台中看到环境变量。