Share on facebook
Share on twitter
Share on linkedin

How to Monitor a VPN Connection in AWS using Lambda

A Cloud Guru News
A Cloud Guru News

A simple and reliable script to solve a complex problem

When using a service in production, it’s important to have everything monitored so you’re notified when things aren’t running smoothly. But at this moment, AWS has no way to monitor and notify when a tunnel is down in your VPN Connection.

In order to solve this situation, I wrote a simple and reliable Lambda function in Python to return an error when both tunnels are down.

First, let’s review what needs to be created in order to setup a VPN Connection:

  1. A Customer Gateway per endpoint
  2. A VPN Gateway and attach it to your VPC
More info on creating VPN tunnels can be found here.

Using this approach, 2 tunnels will automatically be created for redundancy.

In some cases, both tunnels can’t be configured — usually because it’s not supported by a Customer Gateway (endpoint). As a result, one of the tunnels will be shown as DOWN. To accommodate this situation, our solution always looks for 2 tunnels DOWN before failing and notifying the SNS Topic.

AWS Lambda lets you run code without provisioning or managing servers.

The definition of Lambda is something quite new — and mind blowing — especially for people like me who come from the old school of building servers in a data center using physical hard drives and network interface cards. The simplicity of Lambda is very powerful.

“Simplicity is prerequisite for reliability.”

― Edsger W. Dijkstra

The script below is simple and reliable way to solve a complex problem. It offers a simple way to return a fail notification if both tunnels are down. If you find a way to improve the script, please feel free to modify it and send a comment in my gist.

You can use the CloudFormation template I created to easily deploy the script. You just need to upload the zip file to S3, then deploy the CFN Template.

When using the CloudFormation template, be sure to upload the python script as “vpnChecker.py.zip” to your S3 Bucket.

Below is the Python code you need to upload to S3 — credits to Chris Funderburg for the v0.2.0.

import json
import boto3
import datetime
import sys
ec2 = boto3.client('ec2')
cw  = boto3.client('cloudwatch')
version = '0.2.0'
def return_value(dict, key):
    for d in dict:
        if d['Key'] == key:
            return d['Value']
        else:
            return "unknown"
def put_cloudwatch_metric(metric_name, value, vgw, cgw):
    cw.put_metric_data(
        Namespace='VPNStatus',
        MetricData=[{
            'MetricName': metric_name,
            'Value': value,
            'Unit': 'Count',
            'Dimensions': [
                {
                    'Name': 'VGW',
                    'Value': vgw
                },
                {
                    'Name': 'CGW',
                    'Value': cgw
                }
            ]
        }]
    )
def lambda_handler(event, context):
    num_connections = 0
    tunnels = ec2.describe_vpn_connections()['VpnConnections']
    for tunnel in tunnels:
if tunnel['State'] == 'available':
          num_connections += 1
          active_tunnels = 0
          if tunnel['VgwTelemetry'][0]['Status'] == 'UP':
              active_tunnels += 1
          if tunnel['VgwTelemetry'][1]['Status'] == 'UP':
              active_tunnels += 1
          
          put_cloudwatch_metric(
                            tunnel['VpnConnectionId'] + '-' + return_value(tunnel['Tags'], 'Name'),
                            active_tunnels,
                            tunnel['VpnGatewayId'],
                            tunnel['CustomerGatewayId'])
print tunnel['VpnConnectionId']
      print (return_value(tunnel['Tags'], 'Name'))
      print "  " + tunnel['State']
      print "    " + tunnel['VgwTelemetry'][0]['Status']
      print "    " + tunnel['VgwTelemetry'][1]['Status']
      print " "

Please contact me directly if you need any assistance on how to deploy and use these scripts. Feel free to add me on LinkedIn or follow me on Twitter.


The A Cloud Guru specialty course on Networking from a well recognized guru Adrian Cantrill, will give you a deep dive on all the ins and outs of AWS Networking.

Check out the AWS courses from A Cloud Guru to level-up your cloud computing skills, or visit their community forums to connect with industry experts.

Recommended

Get more insights, news, and assorted awesomeness around all things cloud learning.

Get Started
Who’s going to be learning?
Sign In
Welcome Back!
Thanks for reaching out!

You’ll hear from us shortly. In the meantime, why not check out what our customers have to say about ACG?

How many seats do you need?

  • $499 USD per seat per year
  • Billed Annually
  • Renews in 12 months

Ready to accelerate learning?

For over 25 licenses, a member of our sales team will walk you through a custom tailored solution for your business.


$2,495.00

Checkout