Skip to content

Instantly share code, notes, and snippets.

@YakDriver
Created February 22, 2018 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YakDriver/5685e43da04d480fd8fa8e73c47069dc to your computer and use it in GitHub Desktop.
Save YakDriver/5685e43da04d480fd8fa8e73c47069dc to your computer and use it in GitHub Desktop.
Manage security groups (shell script) from AWS CLI
#!/bin/bash
# Errors are thrown if Terraform is given the name of an existing security group.
# One solution is to find the existing security group and delete it. (That will fail if any instances are associated.)
# This installs jq, finds security group id, deletes security group.
#
security_group_name=your_sg
# 1. Install jq
curl -L "https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64" -o jq.dms && chmod +x jq.dms
# 2. Find security group id
sg_id="$(aws ec2 describe-security-groups --filters Name=group-name,Values=${security_group_name} | ./jq.dms -r '.SecurityGroups[0].GroupId')"
# 3. Delete security group using id
if [ "${sg_id}" != "null" ] && [ -n "${sg_id}" ] ; then #jq can return "null" if no group found
aws ec2 delete-security-group --group-id "${sg_id}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment