How to iterate over all aws_instances in terraform?

Viewed 2075

I'm relatively new to terraform and I'm trying to iterate over all aws_instances to apply a null_resource. Can you use multiple splats to access all instances, regardless of their names?

The EC2 instances are broken down by three types:

aws_instance.web.* (3 instances)
aws_instance.app.* (3 instances)
aws_instance.db.*  (2 instances)

Here's my attempt to apply a null_resource to all eight aws_instances:

resource "null_resource" "install_security_package" {

  #count = "${length(aws_instance)}" #terraform error: resource count can't reference variable: aws_instance
  #count = "${length(aws_instance.*)}" #terraform error: resource variables must be three parts: TYPE.NAME.ATTR
  count = "${length(aws_instance.*.*)}" #terraform error: unknown resource 'aws_instance.*'

  connection {
    type        = "ssh"
    host        = "${element(aws_instance.*.private_ip, count.index)}"
    user        = "${lookup(var.user, var.platform)}"
    private_key = "${file("${var.private_key_path}")}"
    timeout     = "2m"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo rpm -Uvh http://www.example.com/security/repo/security_baseline.rpm",
    ]
  }
}
1 Answers
Related