Accessing the aws_instances private ip addresses from other instances

I have a aws_instance resourse defined like this:

  • foo.tf
resource "aws_instance" "foo" {
  count                  = var.instance_count
  ...
}

Then I have a my outputs like this:

  • output.tf
output "seeds" {
  ...
  value = [ aws_instance.foo.1.private_ip, aws_instance.foo.2.private_ip ]
}

And that works perfectly. Now assuming that my count variable has 10 nodes, how can I access the private ip addresses of my seeds from all 10 instances? I would like to be able to access the seeds list from the user_data on each of the 10 instances.

You can use either a for expression:

output "for_seeds" {
  value = [ for i in aws_instance.foo: i.private_ip ]
}

Or the equivalent splat expression:

output "for_seeds" {
  value = aws_instance.foo.*.private_ip
}

Thanks @alisdair. Do you know how would I be able to access that seed list from within user_data on all 10 instances?

That sounds like it would be a circular reference. The private IP is only available after the instance has been created, so you can’t use that as user data to create the instance.

I might be misunderstanding your intention, but I don’t think doing what you describe is possible. Why do you want to use the group of private IP addresses in user data? Perhaps there’s an alternative approach to solving the bigger problem.

I’m trying to setup a 10 node Cassandra cluster and I’m using user_data to populate the cassandra.yaml. In this file, I need to list 2 out of the 10 ec2 instances as the seeds for the whole cluster.

Hi @crdiaz324!

I was recently helping someone with a similar problem over on Stack Overflow:

I think your goal here is similar enough that hopefully my answer there will also help you find a solution to the circular dependency. In that case I assumed that all of the instances would be what you call “seed nodes” in the Cassandra terminology, though I think it would be possible to adapt that overall approach to take only the first two items, once you’ve solved the root problem of allocating IP addresses separately from starting the instances.

1 Like