Content of scripts/test.sh
:
#!/bin/bash
# Exit if any of the intermediate steps fail
set -e
# jq will ensure that the values are properly quoted
# and escaped for consumption by the shell.
eval "$(jq -r '@sh "ASG_NAME=\(.asg_name) REGION=\(.region) DC=\(.desired_capacity)"')"
# getting current desired count of autoscaling
value=$(aws autoscaling describe-auto-scaling-groups --output json --region $REGION --max-items 1000| jq '.AutoScalingGroups[]|select(.AutoScalingGroupName|test("'''$ASG_NAME'''."))|.DesiredCapacity')
# if value is empty or non-integer, default to input-desired-capacity
re='^[0-9]+$'
if ! [[ $value =~ $re ]]; then
value=$DC
fi
# if value is less than input-desired-capacity, then use input-desired-capacity
if [[ $value -le $DC ]]; then
value=$DC
fi
# Making json
echo '{"desired_count": "'''${value}'''"}' | jq .
Calling above script by external data source:
data "external" "test" {
program = ["bash", "${path.root}/scripts/test.sh"]
query {
asg_name = "NAME_OF_ASG_TO_BE_grepED"
region = "${var.aws_region}"
desired_capacity = "${var.desired_capacity}"
}
}
Using this as desired_capacity inside asg resource/module:
resource "aws_autoscaling_group" "foo" {
...
desired_capacity = "${data.external.test.result.desired_count}"
...