简体   繁体   中英

Using Count in Terraform to create Launch Configuration

I have 3 different version of an AMI, for 3 different nodes in a cluster.

data "aws_ami" "node1"
{
  # Use the most recent AMI that matches the pattern below in 'values'.
  most_recent = true

  filter {
    name = "name"
    values = ["AMI_node1*"]
  }

  filter {
    name = "tag:version"
    values = ["${var.node1_version}"]
  }

}

data "aws_ami" "node2"
{
  # Use the most recent AMI that matches the pattern below in 'values'.
  most_recent = true

  filter {
    name = "name"
    values = ["AMI_node2*"]
  }

  filter {
    name = "tag:version"
    values = ["${var.node2_version}"]
  }

}

data "aws_ami" "node3"
{
  ...
}

I would like to create 3 different Launch Configuration and Auto Scaling Group using each of the AMIs respectively.

resource "aws_launch_configuration" "node"
{
  count = "${local.node_instance_count}"
  # Name-prefix must be used otherwise terraform fails to perform updates to existing launch configurations due to
  # a name conflict: LCs are immutable and the LC cannot be destroyed without destroying attached ASGs as well, which
  # terraform will not do. Using name-prefix lets a new LC be created and swapped into the ASG.
  name_prefix = "${var.environment_name}-node${count.index + 1}-"
  image_id = "${data.aws_ami.node[count.index].image_id}"
  instance_type = "${var.default_ec2_instance_type}"
 ...
}

However, I am not able use aws_ami.node1 , aws_ami.node2 , aws_ami.node3 using the cound.index the way I have shown above. I get the following error:

Error reading config for aws_launch_configuration[node]: parse error at 1:39: expected "}" but found "."

Is there another way I can do this in Terraform?

Indexing data sources isn't something that's doable; at the moment.

You're likely better off simply dropping the data sources you've defined and codifying the image IDs into a Terraform map variable.

variable "node_image_ids" {
  type        = "map"

  default = {
    "node1" = "1234434"
    "node2" = "1233334"
    "node3" = "1222434"
  }
}

Then, consume it:

image_id = "${lookup(var.node_image_ids, concat("node", count.index), "some_default_image_id")}"

The downside of this is that you'll need to manually update the image id when images are upgraded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM