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:
At the Google Cloud Console:
At the Virtual Machine instance:
- SSH into the Virtual Machine instance that will serve as a private Network Address Translation instance.
- Open the system configuration file:
- sudo nano /etc/sysctl.conf
- Enable IP forwarding at the Guest OS level using sudo sysctl net.ipv4.conf.all.forwarding=1.
- If iptables is not already installed, run:
- sudo apt-get update
- sudo apt-get install iptables.
- Identify the interface names of the Virtual Machine instance that connects to the outbound network using ip route of ifconfig -a.
- 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
- 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:
- Go to the Virtual Private Cloud Routes page.
- In the Route Management tab, click Create route.
- 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.
- Click Create.
- Then, go to the VPC Network Peering page.
- Select the Virtual Private Cloud peering with the servicenetworking Peered Virtual Private Cloud network.
- Choose Export custom routes.
- 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.