Search code examples
amazon-web-servicesamazon-ec2terraformping

Ping between EC2 with Terraform


Any idea on how to ping between EC2 instances that are being created via Terraform? I'm creating them like this:

resource "aws_instance" "machines" {
  count = 100
  instance_type = "t3.micro"
  subnet_id = var.subnetID
...........................
  tags = {
    Name = "machine-${count.index}"
  }
}

But my question is, if I want to go ahead and ping machine 2 from 1, 3 from 2 etc. etc. how can I do that? And I also need the ping results as Terraform outputs. And can I get the output as a value? The machines are Windows btw.

Tried to create 100 machines via Terraform and then wanted to ping each other from the previous one(e.g. pring 100 from 99, 99 from 98, 98 from 97, ..., 3 from 2, 2 from 1, 1 from 0 and 0 from 100). Also tried to get response as output.


Solution

  • Directly doing this scenario purely on instance creation will be very challenging. The option you have for executing code in the instance on creation is via the user_data argument, but it's executed in the background, after Terraform has finished provisioning the resources.

    Maybe if you set the machines DNS first, then you can try something, but it will have it's limits.

    It would make more sense to use some automation for that, since you'll need the instances names or IPs after they're created, and you can repeat that as much as you like.

    One option is to use Systems Manager Run Command, which optionally has it's own Terraform resource ssm_document. You can get the first output from Terraform with the instances identification (or better, get it directly from the APIs), and execute a second module to run your ping commands from there.

    Another similar option still on AWS is with the AWS OpsWorks service. You'll have access to operations services that you can use for that purpose.