amazon ec2 - How to iterate over all aws_instances in terraform? -
i'm relatively new terraform , i'm trying iterate on aws_instances apply null_resource. can use multiple splats access instances, regardless of names?
the ec2 instances broken down 3 types:
aws_instance.web.* (3 instances) aws_instance.app.* (3 instances) aws_instance.db.* (2 instances)
here's attempt apply null_resource 8 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 3 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", ] } }
it not possible match resources of given type. "splat" syntax, you've seen, allows selecting of instances created particular resource block.
the closest can terraform today concatenate different resources:
concat(aws_instance.web.*.private_ip, aws_instance.app.*.private_ip, aws_instance.db.*.private_ip)
in current version of terraform of answer necessary use of workarounds shared in github issue #4084 in order avoid duplicating complex expression in multiple places. forthcoming feature called local values make simpler in near future, allowing list given name re-used in multiple places:
# won't work until terraform pr#15449 merged , released locals { aws_instance_addrs = "${concat(aws_instance.web.*.private_ip, aws_instance.app.*.private_ip, aws_instance.db.*.private_ip)}" } resource "null_resource" "install_security_package" { count = "${length(local.aws_instance_addrs)}" connection { type = "ssh" host = "${local.aws_instance_addrs[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", ] } }
Comments
Post a Comment