Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform looping a module

I have a module with in my terraform file that created some Database servers that does a few things.

First, it creates an auto scaling group to use a specific image, then it creates some EBS volumes and attaches them and then adds some lambda code so on launch the instances get registered to route 53. So in all about 80 lines of text.

Extract

module "systemt-sql-db01" {
  source          = "localmodules/tf-aws-asg"
  name            = "${var.envname}-sys-db01"
  envname         = "${var.envname}"
  service         = "dbpx"
  ami_id          = "${data.aws_ami.app_sqlproxy.id}"
  user_data       = "${data.template_cloudinit_config.config-enforcement-sqlproxy.rendered}"
   #subnets         = ["${module.subnets-enforcement.web_private_subnets}"]
  subnets         = ["${element(module.subnets-enforcement.web_private_subnets, 1)}"]
  security_groups = ["${aws_security_group.unfiltered-egress-sg.id}", "${aws_security_group.sysopssg.id}", "${aws_security_group.system-sqlproxy.id}"]
  key_name        = "${var.keypair}"    

  load_balancers       = ["${var.envname}-enf-dbpx-int-elb"]
  iam_instance_profile = "${module.iam_profile_generic.profile_arn}"

  instance_type = "${var.enforcement_instancesize_dbpx}"

  min = 0
  max = 0
}

And I then have two parameter files one that I call when launching to pre production and one called when launching to production. I don't want these to contain anything other than variables.

The problem is that for production I need to call the module twice, but for production I need it called three times.

People talk about a count function for modules but I don't think this is possible as yet. Can anyone suggest any other ways to do this? What I would like is to be able in my parameter file to set a list variable of all the DB ASG names, and then loop through this calling the module each time.

I hope that makes sense?

thank you

like image 929
DevilWAH Avatar asked Jul 10 '17 13:07

DevilWAH


1 Answers

EDIT Looping in modules is in beta for Terraform 0.13 (https://discuss.hashicorp.com/t/terraform-0-13-beta-released/9555).

This is a highly requested feature in Terraform and as mentioned it is not yet supported. Later releases of Terraform v0.12 will introduce this feature (https://www.hashicorp.com/blog/hashicorp-terraform-0-12-preview-for-and-for-each).

I had a similar problem where I had to create multiple KMS keys for multiple accounts from a base KMS module. I ended up creating a second module that uses the core KMS module, this second module had many instances of the core module, but only required me to input the account details once.

This is still not ideal, but it worked well enough without over complicating things.

like image 144
phzietsman Avatar answered Sep 28 '22 04:09

phzietsman