当前位置:   article > 正文

【Terraform学习】Terraform_count使用(Terraform配置语言学习)_terraform count

terraform count

一、简单使用:对于一些需要起多个重复的实例有用

variable “elb_names” {
        type = list
        default = ["a", "b", "c"]
}
resource "aws_iam_user" "lb" {
        name = var.elb_names[count.index]
        count = 3
        path = "/sys/"
}

当我们在Terraform 模板里面创建资源的时候,如果有多个重复的资源,我们可以通过count来指定个数,他会自动执行一个类似for loop的循环,然后我们可以通过count.index 来指向他每次循环的索引值。从编程的思维来理解,就是我们执行一个for 循环, 每次循环获取index的值,从一个对应长度的数组里面获取元素值赋给name这个参数

使用count配置 EC2

  • 接下来,编辑main.tf以使用count根据新变量的值和私有子网的数量为 EC2 实例预置资源块

 resource "aws_instance" "app" {
+  count = var.instances_per_subnet * length(module.vpc.private_subnets)
+
   ami           = data.aws_ami.amazon_linux.id
   instance_type = var.instance_type

-  subnet_id              = module.vpc.private_subnets[0]
+  subnet_id              = module.vpc.private_subnets[count.index % length(module.vpc.private_subnets)]
   vpc_security_group_ids = [module.app_security_group.this_security_group_id]

   ## ...

 }

更新负载均衡器

  • 更新elb_http块中的负载均衡器配置以将实例附加到负载均衡器

-  number_of_instances = 2
-  instances           = [aws_instance.app_a.id, aws_instance.app_b.id]
+  number_of_instances = length(aws_instance.app)
+  instances           = aws_instance.app.*.id
  • 更新outputs.tf以引用新块aws_instance.app

 output "instance_ids" {
   description = "IDs of EC2 instances"
-  value       = [aws_instance.app_a.id, aws_instance.app_b.id]
+  value       = aws_instance.app.*.id
 }

应用配置

  • 立即应用此配置。Terraform 将输出 VPC、负载均衡器和实例的值

    • terraform apply

## ...

Apply complete! Resources: 8 added, 0 changed, 4 destroyed.

Outputs:

instance_ids = [
  "i-0bc4309c117df766a",
  "i-0aaa6de2b610ae749",
  "i-035ff2723aace0f12",
  "i-02640c564d3f08152",
]
public_dns_name = "lb-yksg-client-webapp-dev-702243816.us-west-2.elb.amazonaws.com"
vpc_arn = "arn:aws:ec2:us-west-2:561656980159:vpc/vpc-0195a5982b1ad302b"
  • 现在,您已使用变量count配置了 EC2 实例数

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号