Skip to content

Instantly share code, notes, and snippets.

@pll
Created July 16, 2015 20:34
Show Gist options
  • Save pll/52dcb7ca69e7b0f962cc to your computer and use it in GitHub Desktop.
Save pll/52dcb7ca69e7b0f962cc to your computer and use it in GitHub Desktop.
using count/count.index to spin up multiple instances with EIPs.
######################################################################
## Set up NAT instances
###
resource "aws_instance" "nat" {
ami = "${var.aws_nat_ami}"
count = 2
associate_public_ip_address = true
availability_zone = "${lookup(var.az, count.index)}"
instance_type = "t2.micro"
key_name = "${var.aws_key_name}"
security_groups = ["${aws_security_group.sg.id}"]
source_dest_check = false
subnet_id = "${aws_subnet.pub1.id}"
tags = {
"Name" = "${var.env}-nat-${count.index}"
"owner" = "${var.owner}"
"email" = "${var.email}"
"group" = "${var.group}"
"env" = "${var.env}"
}
connection {
user = "ec2-user"
key_file = "~/.ssh/${var.aws_key_name}.pem"
agent = false
}
provisioner "remote-exec" {
inline = [
"sudo iptables -t nat -A POSTROUTING -j MASQUERADE",
"echo 1 |sudo tee /proc/sys/net/ipv4/conf/all/forwarding > /dev/null",
]
}
}
output "nat" {
value = "${aws_instance.nat.${count.index}.public_ip}"
}
resource "aws_eip" "nat-eip" {
instance = "${aws_instance.nat.${count.index}.id}"
vpc = true
depends_on = ["aws_instance.nat.$count.index}"]
}
output "nat-eip" {
value = "${aws_eip.nat-eip.${count.index}.public_ip}"
}
@thegedge
Copy link

A few things:

  1. If var.az is a list, you should use element instead of lookup. If it is a map then it will need numerical keys ranging from 0 to the value of count (in this case, 2). Just a heads-up because I can't see the value of ${var.az} here 😃
  2. aws_eip.nat-eip will need a count equal to the aws_instance.nat's count.
  3. I don't think you need the depends_on for the EIP, since it should depend on it implicitly through instance.
  4. I think interpolations inside of interpolations works, but I personally don't trust it so I'd rewrite the instance line to be instance = ${element(aws_instance.nat.*.id, count.index)}
  5. Similarly for your output, you can't have lists, so I'd rewrite it to be a comma-separated list: value = ${join(",", aws_eip.nat-eip.*.public_ip)}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment