Aws_autoscaling_group (instances)

Is there a reason that this resource doesn’t have an attribute for instances in it?

I’m trying to avoid having to run:

aws autoscaling describe-auto-scaling-instances --region us-east-1 --output text \
--query "AutoScalingInstances[?AutoScalingGroupName=='ASG-GROUP-NAME'].InstanceId" \
| xargs -n1 aws ec2 describe-instances --instance-ids $ID --region us-east-1 \
--query "Reservations[].Instances[].PrivateIpAddress" --output text

as you can see my goal is to return the private IP of the instances created as part of the ASG.

Hi @cdenneen,

The problem in this case is that the set of instances for an autoscaling group changes dynamically after the autoscaling group is created. Typically immediately after the hashicorp/aws provider has created the autoscaling group it has no instances at all (because EC2 instances take several minutes to launch) and so if the provider tried to populate the set of EC2 instances it would usually appear as empty.

Even if it didn’t initially appear as empty, the set would still become invalid as soon as EC2 autoscaling stops or starts an instance at runtime in response to an asynchronous event such as a hardware failure. Although Terraform is managing the autoscaling group, the individual instances are not managed directly by Terraform, and so the provider exporting a snapshot of them here would not actually be useful.

Instead it’s more typical to leave Terraform totally ignorant of the EC2 instances and let autoscaling alone deal with managing them. If you need to take special actions when the instances are created and destroyed then you can either arrange for the instances to take that special action themselves on first boot, or you can use Lifecycle Hooks to trigger an external action such as running an AWS Lambda function. You can use Terraform to arrange for those special actions to occur, but Terraform will only be managing the system that takes those actions, not taking the actions itself.

If you do need to work directly with the individual instances then I would suggest not using autoscaling at all and instead managing individual instances directly with aws_instance. This does mean that your system won’t be able to react dynamically to events like autoscaling would, but it also means that your set of available EC2 instances will only change in response to Terraform running and so it’s possible for Terraform to take other actions at the same time as creating or destroying them.