基于 terraform 中 count.index 的属性差异 [英] Variance in attributes based on count.index in terraform

查看:20
本文介绍了基于 terraform 中 count.index 的属性差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Hashicorp terraform 在 AWS 上创建一个 MySQL 集群.我创建了一个名为 mysql 的模块,并希望将创建的第一个实例标记为 master.但是,根据 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:

模块目前不支持 count 参数.

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
}

这会引发错误:

$  project git:(master) ✗ terraform plan

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

我在 mysql 模块和根模块的 variables.tf 文件中声明了必要的变量.我该如何解决这个问题?提前感谢您的帮助!

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!

推荐答案

你在 module 资源中有 count 的方式会推断你想要创建 3 个模块,而不是创建的模块内的资源超过 3 个.您可以从 module 资源中规定计数,但任何使用 count.index 的逻辑都需要位于模块内.

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"}"
  }
}

这篇关于基于 terraform 中 count.index 的属性差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆