EC2: New instances and firewalls

In: Linux

30 Jan 2010

We hold much of our server configuration within the office, which is restricted down by iptables. As such when spawning new instances on EC2 we need to allow access to our internal network via iptables, to allow nodes to connect to the office and configure themselves.

The following script can be run within a crontab to automatically add the nodes to your firewall.
Alternatively you could add a wrapper, whilst creating these, although this is not as nice as using elasticfox etc.

cron.ec2.firewall.sh

#!/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

Comment Form

About this blog

I have been a developer for roughly 10 years and have worked with an extensive range of technologies. Whilst working for relatively small companies, I have worked with all aspects of the development life cycle, which has given me a broad and in-depth experience.