Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variance in attributes based on count.index in terraform

Tags:

terraform

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!

like image 860
eternaltyro Avatar asked Nov 15 '25 18:11

eternaltyro


2 Answers

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"}"
  }
}
like image 112
Nathan Smith Avatar answered Nov 18 '25 19:11

Nathan Smith


Since Terraform 0.13 you can use either for_each or count to create multiple instances of a module.

variable "regions" {
  type = map(object({
    region            = string
    network           = string
    subnetwork        = string
    ip_range_pods     = string
    ip_range_services = string
  }))
}

module "kubernetes_cluster" {
  source   = "terraform-google-modules/kubernetes-engine/google"
  for_each = var.regions

  project_id        = var.project_id
  name              = each.key
  region            = each.value.region
  network           = each.value.network
  subnetwork        = each.value.subnetwork
  ip_range_pods     = each.value.ip_range_pods
  ip_range_services = each.value.ip_range_services
}

Code snipped from https://github.com/hashicorp/terraform/tree/guide-v0.13-beta/module-repetition

Official documentation https://www.terraform.io/docs/configuration/modules.html

like image 22
lars Avatar answered Nov 18 '25 19:11

lars



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!