Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass aws_elastic_beanstalk_environment settings to a Terraform module

I'm using a Terraform module to manage AWS Elastic Beanstalk applications and environments, and want to pass a list of environment variables to the module.

For lack of a better solution, I'm currently passing in a flat list of names and values, and declare a fixed number of setting stanzas (see below). This seems to work, unless of course someone's going to pass in more environment variables than I expected.

So - is there a better way to achieve this?

# file: main.tf
variable env_vars {
  default = ["FIRST_ENV_VAR", "1", "SECOND_ENV_VAR", "2"]
}

provider "aws" {
  region = "eu-central-1"
}

module "beanstalk-app" {
  source   = "./beanstalk"
  env_vars = "${var.env_vars}"
}

# file: beanstalk/main.tf
variable "env_vars" {
  type = "list"
}

resource "aws_elastic_beanstalk_application" "app" {
  name = "myapp"
}

resource "aws_elastic_beanstalk_environment" "env" {
  name                = "myapp-env"
  application         = "${aws_elastic_beanstalk_application.app.name}"
  solution_stack_name = "64bit Amazon Linux 2016.03 v2.1.3 running Tomcat 8 Java 8"

  setting {
    namespace = "aws:elasticbeanstalk:application:environment"
    name      = "${element(var.env_vars, 0)}"
    value     = "${element(var.env_vars, 1)}"
  }

  setting {
    namespace = "aws:elasticbeanstalk:application:environment"
    name      = "${element(var.env_vars, 2)}"
    value     = "${element(var.env_vars, 3)}"
  }

  setting {
    namespace = "aws:elasticbeanstalk:application:environment"
    name      = "${element(var.env_vars, 4)}"
    value     = "${element(var.env_vars, 5)}"
  }
}
like image 1000
otto.poellath Avatar asked Aug 27 '16 19:08

otto.poellath


1 Answers

In HCL repeated object blocks are equivalent to a list (see here . Therefore you can pass a variable (list of maps) to settings.

variable "settings" {
    type = "list"
    default = [
    {
      namespace = "aws:elasticbeanstalk:application:environment"
      name      = "FOO"
      value     = "BAR"
    },
    {
      namespace = "aws:elasticbeanstalk:application:environment"
      name      = "BAZ"
      value     = "HAZ"
    },
  ]
}

resource "aws_elastic_beanstalk_environment" "env" {
  name                = "myapp-env"
   application         = "${aws_elastic_beanstalk_application.app.name}"
  solution_stack_name = "64bit Amazon Linux 2016.03 v2.1.3 running Tomcat 8 Java 8"
  setting = ["${var.settings}"]
}
like image 71
Valentin Avatar answered Sep 19 '22 00:09

Valentin