Skip to content
This repository has been archived by the owner on Jul 20, 2024. It is now read-only.

Fix NAT not working 2022-07 #51

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,9 @@ resource "aws_iam_role_policy" "eni" {
{
"Effect": "Allow",
"Action": [
"ec2:AttachNetworkInterface"
"ec2:AttachNetworkInterface",
"ec2:ModifyNetworkInterfaceAttribute",
"ec2:DescribeInstances"
],
"Resource": "*"
}
Expand Down
17 changes: 15 additions & 2 deletions runonce.sh
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
#!/bin/bash -x

sudo yum install -y jq

INSTANCE_ID="$(/opt/aws/bin/ec2-metadata -i | cut -d' ' -f2)"
REGION="$(/opt/aws/bin/ec2-metadata -z | sed 's/placement: \(.*\).$/\1/')"

# attach the ENI
aws ec2 attach-network-interface \
--region "$(/opt/aws/bin/ec2-metadata -z | sed 's/placement: \(.*\).$/\1/')" \
--instance-id "$(/opt/aws/bin/ec2-metadata -i | cut -d' ' -f2)" \
--region "$REGION" \
--instance-id "$INSTANCE_ID" \
--device-index 1 \
--network-interface-id "${eni_id}"

# Disable source/destination checks
for i in $(aws ec2 describe-instances --region "$REGION" --filter '[{"Name": "instance-id", "Values": ["'$INSTANCE_ID'"]}]' | jq -r .Reservations[0].Instances[0].NetworkInterfaces[].NetworkInterfaceId); do
aws ec2 modify-network-interface-attribute \
--region "$REGION" \
--network-interface-id "$i" \
--no-source-dest-check
done

# start SNAT
systemctl enable snat
systemctl start snat
15 changes: 12 additions & 3 deletions snat.sh
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
#!/bin/bash
set -x

# wait for eth1
# Wait for eth1
while ! ip link show dev eth1; do
sleep 1
done

# enable IP forwarding and NAT
# Enable IP forwarding
sysctl -q -w net.ipv4.ip_forward=1

# Disable ICMP redirects on eth1
sysctl -q -w net.ipv4.conf.eth1.send_redirects=0

# Configure NAT
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE

# Disable reverse path protection
for i in $(find /proc/sys/net/ipv4/conf/ -name rp_filter) ; do
echo 0 > $i;
done

# prevent setting the default route to eth0 after reboot
rm -f /etc/sysconfig/network-scripts/ifcfg-eth0

Expand All @@ -21,4 +30,4 @@ ip route del default dev eth0
curl --retry 10 http://www.example.com

# reestablish connections
systemctl restart amazon-ssm-agent.service
systemctl restart amazon-ssm-agent.service