How to configure a Virtual Machine as a private Network Address Translation instance using iptables

Problem

How can you set up a Virtual Machine for Network Address Translation between two private IP ranges to reach Service Networking services in Google Cloud from on-premises.

Environment

  • Running a Hybrid connectivity solution such as Cloud Virtual Private Network or Cloud Interconnect, the outbound network.
  • A Virtual Private Cloud Peering with Service Networking, the peered network.
  • A Google Compute Engine instance running a supported version of Debian.
  • IP forwarding Virtual Machine property is enabled.
  • The Virtual Machine instance has at least two virtual NICs to the outbound Virtual Private Cloud network and the peered Virtual Private Cloud network.

Solution

The following is an example of how to configure a Virtual Machine to provide private Network Address Translation using iptables MASQUERADING. However, please note that this is not supported or endorsed by Google Cloud and should be used with caution.

At the Virtual Machine instance:
  1. SSH into the Virtual Machine instance that will serve as a private Network Address Translation instance.
  2. Open the system configuration file:
    • sudo nano /etc/sysctl.conf
  3. Enable IP forwarding at the Guest OS level using sudo sysctl net.ipv4.conf.all.forwarding=1.
  4. If iptables is not already installed, run:
    • sudo apt-get update
    • sudo apt-get install iptables.
  5. Identify the interface names of the Virtual Machine instance that connects to the outbound network using ip route of ifconfig -a.
  6. Replace INTERFACE_NAME with the name of the outbound interface in the following command:
    • sudo iptables --table nat --append POSTROUTING --out-interface  [INTERFACE_NAME] -j MASQUERADE
  7. Configure a static route that points the IP address ranges at on-premises to the IP address of the default gateway of the outbound interface’s VPC network:
    • sudo ip route add [IP_RANGE] via [DEFAULT_GATEWAY] dev [INTERFACE_NAME]

At the Google Cloud Console:
  1. Go to the Virtual Private Cloud Routes page.
  2. In the Route Management tab, click Create route.
  3. Add a static route to the destination IP address range of the on-premises network with the Virtual Machine instance as the next hop. You need to consider whether this affects other instances as well.
  4. Click Create.
  5. Then, go to the VPC Network Peering page.
  6. Select the Virtual Private Cloud peering with the servicenetworking Peered Virtual Private Cloud network.
  7. Choose Export custom routes.
  8. Click Save.

Cause

There might be situations where you need to reach a Google Cloud service from on-premises using an specific IP address range. Generally, you can advertise Virtual Private Cloud peering subnet ranges to on-premises using Cloud Router.