如何在Terraform中正确使用Count并选择多个az子网

时间:2018-04-18 16:03:29

标签: amazon-web-services terraform terraform-provider-aws

我正在尝试实现一个模块,我试图在已创建的子网中旋转一些实例(通过terraform),但我不知道如何在模块中实际使用count如何从s3 bucket数据源中选择值以在multi-az中旋转实例,这是我在模块目录中的资源看起来像

i

这是实际的模块:

resource "aws_instance" "ec2-instances" {
  count = "${var.count_num }"
  ami = "${data.aws_ami.ubuntu.id}"
  instance_type = "${var.machine_type}"
  key_name = "${var.key_name}"
  #vpc_security_group_ids = ["${aws_security_group.jumpbox-sec-group.id}"]
  vpc_security_group_ids =  ["${var.sec-group}"]
  disable_api_termination = "${var.is_production ? true : false}"
  subnet_id = "${element(var.es_stg_subnets, count.index)}" <--- This won't work , i need to use data-source as s3 
  tags {
    #Name = "${var.master_name}-${count.index+1}"
    Name = "${var.instance-tag}-${count.index+1}"
    Type = "${var.instance-type-tag}"
  }
  root_block_device {
    volume_size = "${var.instance-vol-size}"
    volume_type = "gp2"
  }
}

2 个答案:

答案 0 :(得分:1)

我会考虑使用data source检索您的子网。

  

利用Data Sources

Terraform具有数据源的概念。您可以从AWS获取资源所需的信息。在gen-ec2.tf文件中 -

// In order to get subnets, you need the VPC they belong to.
// Note you can filter on a variety of different tags.
data "aws_vpc" "selected" {
  tags {
    Name = "NameOfVPC"
  }
}

// This will then retrieve all subnet ids based on filter
data "aws_subnet_ids" "private" {
  vpc_id = "${data.aws_vpc.selected.id}"
  tags {
    Tier = "private*"
  }
}

resource "aws_instance" "ec2-instances" {
  count = "${length(data.aws_subnet_ids.private.ids)}"
  ami = "${data.aws_ami.ubuntu.id}"
  instance_type = "${var.machine_type}"
  key_name = "${var.key_name}"
  vpc_security_group_ids =  ["${var.sec-group}"]
  disable_api_termination = "${var.is_production ? true : false}"
  subnet_id = "${element(data.aws_subnet_ids.private.*.ids, count.index)}" 
  tags {
    Name = "${var.instance-tag}-${count.index+1}"
    Type = "${var.instance-type-tag}"
  }
  root_block_device {
    volume_size = "${var.instance-vol-size}"
    volume_type = "gp2"
  }
}

您的模块现在看起来像这样 -

module "grafana-stg" {
  source = "../../modules/services/gen-ec2"
  #ami_id = "${data.aws_ami.ubuntu.id}"
  instance_type = "${var.grafana_machine_type}"
  key_name = "jumpbox"
  vpc_security_group_ids = ["${aws_security_group.grafana-sec-group.id}"]
  disable_api_termination = "${var.is_production ? true : false}"
}

答案 1 :(得分:0)

对于我来说,当我使用Terraform v0.12.5时,波纹管片段效果很好

data "aws_subnet_ids" "public_subnet_list" {
  vpc_id = "${var.vpc_id}"
  tags = {
    Tier = "Public"
  }
}


resource "aws_instance" "example" {
  count         = 2
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  subnet_id     = tolist(data.aws_subnet_ids.public_subnet_list.ids)[count.index]
}