Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mrbenosborne
Last active March 27, 2019 21:25
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 mrbenosborne/0df681e348b09cdb0e13e896ec3e367d to your computer and use it in GitHub Desktop.
Save mrbenosborne/0df681e348b09cdb0e13e896ec3e367d to your computer and use it in GitHub Desktop.
Circle CI - Add and Remove Security Group Rule for servers that are not publicly accessible
#!/bin/bash
# "jq" is required to be installed for this script to work
# and "awscli"
# set security group id from AWS
SecurityGroupID="sg-XXXXXXXX"
# Set the port no
Port=3306
# set network mask
NetworkMask="32"
# set protocol
Protocol="tcp"
# get the external ip of this machine
IP=$(curl -s https://checkip.amazonaws.com)
# add the rule
aws ec2 authorize-security-group-ingress --group-id $SecurityGroupID --protocol $Protocol --port $Port --cidr $IP/$NetworkMask
# <<
# Do Circle CI Work
# <<
# To delete the rule after Circle CI has finished
# check if the rule already exists
current=$(aws ec2 describe-security-groups --group-ids $SecurityGroupID)
CountOfRules=$(echo $current | jq '.SecurityGroups[0].IpPermissions | length')
for (( c=0; c<$CountOfRules; c++ ))
do
FromPort=$(echo $current | jq ".SecurityGroups[0].IpPermissions[$c].FromPort")
ToPort=$(echo $current | jq ".SecurityGroups[0].IpPermissions[$c].ToPort")
CidrIp=$(echo $current | jq -r ".SecurityGroups[0].IpPermissions[$c].IpRanges[0].CidrIp")
CurrentProtocol=$(echo $current | jq -r ".SecurityGroups[0].IpPermissions[$c].IpProtocol")
if [ "$FromPort" == "$Port" ]
then
if [ "$ToPort" == $Port ]
then
if [ "$CidrIp" == "$IP/$NetworkMask" ]
then
if [ "$Protocol" == "$CurrentProtocol" ]
then
echo "> deleting the rule from security group '" $SecurityGroupID "'..."
aws ec2 revoke-security-group-ingress --group-id $SecurityGroupID --protocol $Protocol --port $ToPort --cidr $IP/$NetworkMask
fi
fi
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment