Skip to content

Instantly share code, notes, and snippets.

@rossdakin
Last active August 29, 2015 14:10
Show Gist options
  • Save rossdakin/d7c7fba92089736254a0 to your computer and use it in GitHub Desktop.
Save rossdakin/d7c7fba92089736254a0 to your computer and use it in GitHub Desktop.
Chef cookbook for creating NAT boxes (intended for use with AWS OpsWorks) – does not do any health checks, HA, nor automatic route table (re)configuration.
# my_nat_cookbook/attributes/default.rb
# specify your CIDR in custom JSON somewhere: { "my_nat_cookbook": { "source_cidr": "10.1.0.0/16" } }
default[:deliv_nat][:source_cidr] = '0.0.0.0/0'
default[:deliv_nat][:aws_region] = node[:opsworks][:instance][:region]
default[:deliv_nat][:ec2_instance_id] = node[:opsworks][:instance][:aws_instance_id]
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Resource": "*",
"Action": "ec2:ModifyInstanceAttribute"
}
]
}
# my_nat_cookbook/recipes/default.rb
region = node[:deliv_nat][:aws_region] # e.g. 'us-east-1'
instance_id = node[:deliv_nat][:ec2_instance_id] # 'i-xxxxxxxx'
source = node[:deliv_nat][:source_cidr] # e.g. '10.1.0.0/16'
directory '/etc/sysctl.d'
file '/etc/sysctl.d/nat.conf' do
backup false
content ['net.ipv4.ip_forward = 1',
'net.ipv4.conf.eth0.send_redirects = 0'].join("\n")
end
execute 'sysctl -w net.ipv4.ip_forward=1' do
user 'root'
end
execute 'sysctl -w net.ipv4.conf.eth0.send_redirects=0' do
user 'root'
end
execute "disabling source/destination check for #{instance_id} in #{region}" do
user 'root'
command %Q(aws ec2 modify-instance-attribute
--region #{region}
--instance-id #{instance_id}
--source-dest-check '{"Value":false}').gsub(/\s+/, ' ')
end
execute "configuring iptables masquerading with source network #{source}" do
user 'root'
command %Q(/sbin/iptables
-t nat
-A POSTROUTING
-o eth0
-j MASQUERADE
-s #{source}).gsub(/\s+/, ' ')
end
execute 'persisting iptables configuration to disk' do
user 'root'
command '/sbin/iptables-save > /etc/sysconfig/iptables'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment