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

Share

Comment Form

About this blog

Andrew Johnstone is a software engineer / lead developer working at Everlution Software.

Photostream