Skip to content

Instantly share code, notes, and snippets.

@rahulwa
Created April 18, 2019 20:14
Show Gist options
  • Save rahulwa/91d63154d0238ef7316cbe4d3c6a8e9a to your computer and use it in GitHub Desktop.
Save rahulwa/91d63154d0238ef7316cbe4d3c6a8e9a to your computer and use it in GitHub Desktop.
Found a solution for maintaining autoscaling’s `desired_capacity` in terraform, need to use`External Data Source` with a script

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}"
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment