Skip to content

Instantly share code, notes, and snippets.

@myoung34
Created August 17, 2020 23:38
Show Gist options
  • Save myoung34/fe53f2c045e3f1ff78bbbb765f422286 to your computer and use it in GitHub Desktop.
Save myoung34/fe53f2c045e3f1ff78bbbb765f422286 to your computer and use it in GitHub Desktop.
#!/bin/bash
# shellcheck disable=SC2086,SC2034
vpc_id=$1
pritunl_security_group=$2
[[ -z ${vpc_id} ]] && exit 1
[[ -z ${pritunl_security_group} ]] && exit 1
subnets=$(aws ec2 describe-subnets --filters Name=vpc-id,Values=${vpc_id} | jq -r .Subnets[].SubnetId)
for subnet in ${subnets}; do
# Get ASG
asgs=$(aws autoscaling describe-auto-scaling-groups | jq -rc ".AutoScalingGroups[] | select(.VPCZoneIdentifier | contains(\"${subnet}\"))")
for asg in ${asgs}; do
asg_name=$(echo ${asg} | jq -r .AutoScalingGroupName)
# Get launch template
lt_id=$(echo ${asg} | jq -r .LaunchTemplate.LaunchTemplateId)
lt=$(aws ec2 describe-launch-template-versions --launch-template-id ${lt_id} | jq -s 'sort_by(.LaunchTemplateVersions[].VersionNumber)' | jq .[0].LaunchTemplateVersions[0])
lt_version=$(echo ${lt} | jq -r .VersionNumber)
# set ASG to use latest launch template
aws autoscaling update-auto-scaling-group --auto-scaling-group-name ${asg_name} \
--launch-template LaunchTemplateId=${lt_id},Version=\$Latest
# Remove current .LaunchTemplateData.NetworkInterfaces
lt_data_without_ni=$(echo ${lt} | jq '. | del(.LaunchTemplateData.NetworkInterfaces)')
# Also remove Tags if they exist
lt_data_without_ni_tags=$(echo ${lt_data_without_ni} | jq '. | del(.LaunchTemplateData.TagSpecifications)')
# Add pritunl security group
network_interfaces=$(echo ${lt} | jq -c -r .LaunchTemplateData.NetworkInterfaces[].Groups | sed "s/]/, \"${pritunl_security_group}\"]/")
network_interfaces_str="{\"NetworkInterfaces\": [{\"AssociatePublicIpAddress\": true,\"DeviceIndex\": 0,\"Groups\": ${network_interfaces}}]}"
# Build up volume/instance tags for Name
tag_str="{\"TagSpecifications\": [{\"ResourceType\": \"instance\",\"Tags\": [{\"Key\": \"Name\",\"Value\": \"pritunl\"}]},{\"ResourceType\": \"volume\",\"Tags\": [{\"Key\": \"Name\",\"Value\": \"pritunl\"}]}]}"
# Update .LaunchTemplateData
lt_data=$(echo ${lt_data_without_ni} | jq -c ".LaunchTemplateData + ${network_interfaces_str} + ${tag_str}")
# Bump version and specify new .LaunchTemplateData
aws ec2 create-launch-template-version --launch-template-id ${lt_id} --version-description bump --source-version ${lt_version} --launch-template-data "${lt_data}"
# Cause a cycle
for instance_id in $(aws autoscaling describe-auto-scaling-instances | jq -r ".AutoScalingInstances[] | select(.AutoScalingGroupName == \"${asg_name}\") | .InstanceId"); do
aws ec2 terminate-instances --instance-ids ${instance_id}
done
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment