terraform use count index in module [duplicate]

2019-09-21 10:57发布

This question already has an answer here:

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

2条回答
劫难
2楼-- · 2019-09-21 11:26

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
}
查看更多
地球回转人心会变
3楼-- · 2019-09-21 11:29

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.

查看更多
登录 后发表回答