Variance in attributes based on count.index in terraform

后端 未结 3 1203
-上瘾入骨i
-上瘾入骨i 2020-12-21 10:37

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

相关标签:
3条回答
  • 2020-12-21 11:09

    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"}"
      }
    }
    
    0 讨论(0)
  • 2020-12-21 11:23

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

    0 讨论(0)
  • 2020-12-21 11:26

    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

    0 讨论(0)
提交回复
热议问题