terraform use count index in module [duplicate]

别来无恙 提交于 2019-12-13 23:37:51

问题


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-1 firsttypeinstance-2 firsttypeinstance-3

secondtype-1 secondtype-2

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


回答1:


If you are using terraform 0.12, you are able to use the for loop feature: https://www.terraform.io/docs/configuration/expressions.html#for-expressions

If you are under 0.12(as I do) -- no luck.

Still, adding id to your instances tend to make your infrastructure less "immutable", in my opinion.




回答2:


From terraform doc:

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.

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

module ec2

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

module main

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


来源:https://stackoverflow.com/questions/56241761/terraform-use-count-index-in-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!