How to disconnect Amazon VPN using Lambda

650 Views Asked by At

I want to create Amazon DirectConnect connection as VPN to transfer data from my company network to RDS instance. The connection is not cheap and I certainly don't need it open the whole time. Probably just 10 minutes every day is enough. Is there a way to schedule connect/disconnect event of the VPN connection using Lambda function just like starting/stopping EC2 or RDS instance like below using Python's Boto3 library:

def handler(event, context):

    ec2 = boto3.client('ec2', region_name=region)

    ec2.start_instances(InstanceIds=instances)

Although Boto3 supports DirectConnect, it doesn't seem to have any methods that switch the connection on and off. Is there a way to control the connection?

1

There are 1 best solutions below

1
On

Handler code will look like this

def handler(event, context):
    client = boto3.client('directconnect')
    response = client.delete_connection(
        connectionId='string'
     )

This lambda will just deletes the connection that is charged by the port hour and data transfer charges.

You can create a lambda and automate with a trigger to create and delete connection, if you have a defined time window.

Documentation is available here:

http://boto3.readthedocs.io/en/latest/reference/services/directconnect.html#DirectConnect.Client.delete_connection

EDIT 1:

Associate and Disassociate LAG to Connection:

http://boto3.readthedocs.io/en/latest/reference/services/directconnect.html#DirectConnect.Client.associate_connection_with_lag

http://boto3.readthedocs.io/en/latest/reference/services/directconnect.html#DirectConnect.Client.disassociate_connection_from_lag

You need to check whether the associated port charges does not incur when all the connections are removed. This way you can maintain your connectionid.

Alternatively, you can store your connectionid as a reference in a db and pull from there when needed.

Hope it helps.