terraform 在模块中使用计数索引 [英] terraform use count index in module

查看:42
本文介绍了terraform 在模块中使用计数索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 aws ec2 实例的 terraform 模块中使用 count.index 来以递增顺序命名实例

I want to use the count.index in the terraform module for my aws ec2 instance to name the instance in increment order

file: ec2/main.tf
 resource "aws_instance" "instance"{
    ami = "ami-xxx"
    tags {
     Name = "var.instance"
     }
    count = "var.count"

}

file: ec2instance.tf

module "ec2"{
 source = "./ec2"
 count = 3
 instance_name = "firsttypeinstance-${count.index+1}"
}

module "ec20"{
 source = "./ec2"
 count = 2
 instance_name = "secondtype-${count.index+1}"

}

我希望将实例名称填充为

I want the instance name to be populated as

firsttypeinstance-1firsttypeinstance-2firsttypeinstance-3

firsttypeinstance-1 firsttypeinstance-2 firsttypeinstance-3

secondtype-1secondtype-2

secondtype-1 secondtype-2

但是我得到了我不能在模块中使用计数索引的错误

but i get the error that i cannot use count index in the module

推荐答案

来自terraform doc:

除上述之外,参数名称 countfor_eachlifecycle 目前未被 Terraform 使用,但保留用于计划的未来功能.

In addition to the above, the argument names count, for_each and lifecycle are not currently used by Terraform but are reserved for planned future features.

但是,您可以在模块中创建 my_count 变量并将其用于模块内的资源

however, you could create the my_count variable in your module and use it on resources inside your module

模块 ec2

resource "aws_instance" "instance"{
    ami = "ami-xxx"
    tags {
        Name = "var.instance-${count.index}"
    }
    count = "var.my_count"
}

模块主

module "ec2"{
   source = "./ec2"
   my_count = 3
   instance_name = "firsttypeinstance" ## actually instance prefix
}

这篇关于terraform 在模块中使用计数索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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