#!/bin/bash

IGNORE_REGION='us-west-1'; # For some reason this failed to connect/timeout
PORTS='22 80 3690 4949 8140';

iptables-save > /etc/iptables-config;

ec2-describe-regions | awk '{print $2}' | egrep -v "$IGNORE_REGION"  | while read REGION; do

	echo "$REGION";

	ec2-describe-instances --region $REGION --connection-timeout 3 --request-timeout 3 | \
		grep INSTANCE | \
		while read DATA; do
			EC2_HOST="`echo $DATA | awk '{print $4}'`";
			EC2_PUBLIC_IP="`echo $DATA | awk '{print $15}'`";

			for PORT in $PORTS; do
				MATCH_RULES="\-\-dport $PORT"

				if ! cat /etc/iptables-config | grep "$EC2_HOST" | egrep "$MATCH_RULES"  > /dev/null; then 
					echo -e "\tiptables -A INPUT -s $EC2_PUBLIC_IP/32 -p tcp -m tcp --dport $PORT -m comment --comment "EC2 - 
$EC2_HOST" -j ACCEPT"
					iptables -A INPUT -s $EC2_PUBLIC_IP/32 -p tcp -m tcp --dport $PORT -m comment --comment "EC2 - $EC2_HOST" -j 
ACCEPT
					

				fi;

			done;

		done;

done;
echo "Saving config: /etc/iptables-config"
iptables-save > /etc/iptables-config

