Variance in attributes based on count.index in terraform

跟風遠走 提交于 2019-12-18 09:10:53

问题


I'm using Hashicorp terraform to create a MySQL cluster on AWS. I created a module named mysql and want to tag the first instance created as the master. However, per terraform documentation:

Modules don't currently support the count parameter.

How do I work around this problem? Currently, I have these in my files:

$ cat project/main.tf
module "mysql_cluster" {
  source = "./modules/mysql"
  cluster_role = "${count.index == "0" ? "master" : "slave"}"
}

$ cat project/modules/mysql/main.tf
..
resource "aws_instance" "mysql" {
  ami           = "ami-123456"
  instance_type = "t2.xlarge"
  key_name      = "rsa_2048"

  tags {
    Role = "${var.cluster_role}"
  }

  count = 3
}

This throws an error:

$  project git:(master) ✗ terraform plan

Error: module "mysql_cluster": count variables are only valid within resources

I have the necessary variables declared in the variables.tf files in my mysql module and root module. How do I work around this problem? Thanks in advance for any help!


回答1:


The way you have count in the module resource would infer that you want 3 modules created, rather than 3 resources within the module created. You can stipulate the count from the module resource but any logic using count.index needs to sit within the module.

main.tf

module "mysql_cluster" {
  source          = "./modules/mysql"
  instance_count  = 3
}

mysql.tf

resource "aws_instance" "mysql" {
  count         = "${var.instance_count}"
  ami           = "ami-123456"
  instance_type = "t2.xlarge"
  key_name      = "rsa_2048"

  tags {
    Role        = "${count.index == "0" ? "master" : "slave"}"
  }
}



回答2:


module doesn't have count. It is available at resources only.



来源:https://stackoverflow.com/questions/50186380/variance-in-attributes-based-on-count-index-in-terraform

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!