问题
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