Skip to content

Instantly share code, notes, and snippets.

@davidlu1001
Created August 27, 2019 02:11
Show Gist options
  • Save davidlu1001/59c1d34d12012741582469aaec0d547a to your computer and use it in GitHub Desktop.
Save davidlu1001/59c1d34d12012741582469aaec0d547a to your computer and use it in GitHub Desktop.
Terraform - Use external data source to get EC2 instances count from AutoScaling Group and add EC2 IP to DNS records
data "external" "asg_cousul_count" {
program = [
"/bin/bash",
"scripts/get_asg_instance_count.sh",
]
query = {
region = "us-west-2"
asg_group_name = "asg-consul-production"
}
}
data "aws_instances" "asg_consul_production" {
count = "${data.external.asg_cousul_count.result["count"] == "0" ? 0 : 1}"
instance_tags {
Name = "asg-consul-production"
}
instance_state_names = ["running"]
}
# use multi-answer DNS for asg
resource "aws_route53_record" "consul-server-dns-asg" {
depends_on = ["data.aws_instances.asg_consul_production"]
count = "${data.external.asg_cousul_count.result["count"]}"
zone_id = "XXXXXXXXXXXX"
name = "consul-server.service"
type = "A"
ttl = "300"
allow_overwrite = true
multivalue_answer_routing_policy = true
set_identifier = "route to consul-server asg ${format("%03d", count.index + 1)}"
records = ["${data.aws_instances.asg_consul_production.private_ips[count.index]}"]
}
#!/bin/bash
set -e
eval "$(jq -r '@sh "export ASG_GROUP_NAME=\(.asg_group_name) REGION=\(.region)"')"
instance_ids=`aws autoscaling describe-auto-scaling-instances \
--region "${REGION}" --output text \
--query "AutoScalingInstances[?AutoScalingGroupName=='"${ASG_GROUP_NAME}"'].InstanceId"`
if [[ -z "${instance_ids}" ]]
then
instance_count=0
else
instance_count=`aws ec2 describe-instances --region "${REGION}" --instance-ids \
$(aws autoscaling describe-auto-scaling-instances --region "${REGION}" --output text \
--query "AutoScalingInstances[?AutoScalingGroupName=='"${ASG_GROUP_NAME}"'].InstanceId") \
--query "Reservations[].Instances[].PrivateIpAddress" | jq '. | length'`
fi
jq -n --arg count "$instance_count" '{"count":$count}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment