Here is the code. I simplified some of it. You need an S3 bucket to save the network and an EventBridge to call the script every minute. You can set the Meraki key in the parameters of the lambda function.
from encodings import utf_8
import requests, boto3, os, json
def lambda_handler(event, context😞
api_key = os.environ['Meraki_Key']
header = {"X-Cisco-Meraki-API-Key": api_key, "Content-Type": "application/json"}
response = requests.get(url,headers=header)
s3 = boto3.client('s3')
bucket='[S3 BUCKET]'
key = 'networklist.txt'
for network in response.json():
if network['ip'] != '8.8.8.8' and network['uplink']=="wan1":
print(network['networkId'])
print(network['ip'])
loss=False
for iteration in network['timeSeries']:
if int(0 if iteration['lossPercent'] is None else iteration['lossPercent']) >= 30:
loss=True
print(network_info.json()['name'])
tags = network_info.json()['tags'].split(' ')
if "_primary_down" in tags[1] or "_primary_down" in tags[2]:
print("VPN already swapped")
break
else:
#Ändern der Tags
print("Need to change VPN, recent loss - "+str(iteration['lossPercent']))
if "_primary_up" in tags[1]:
tags[1] = tags[1].split("_up")[0]+"_down"
if "_primary_up" in tags[2]:
tags[2] = tags[2].split("_up")[0]+"_down"
if "_backup_down" in tags[1]:
tags[1] = tags[1].split("_down")[0]+"_up"
if "_backup_down" in tags[2]:
tags[2] = tags[2].split("_down")[0]+"_up"
payload = {'tags': tags[2]+" "+tags[1]}
#Setzen der Tags
#betroffenes Netzwerk wird in S3 Bucket geschrieben
s3.put_object(Body=s3.get_object(Bucket=bucket, Key=key)['Body'].read().decode('utf-8') + "\n" + network['networkId'], Bucket=bucket, Key=key)
break
#Tags werden zurückgesetzt wenn Loss wieder auf 0 zurück geht
if loss==False and network['networkId'] in s3.get_object(Bucket=bucket, Key=key)['Body'].read().decode('utf-8'😞
print("Primary VPN healthy again..swapping back")
tags = network_info.json()['tags'].split(' ')
if "_primary_down" in tags[1]:
tags[1] = tags[1].split("_down")[0]+"_up"
if "_primary_down" in tags[2]:
tags[2] = tags[2].split("_down")[0]+"_up"
if "_backup_up" in tags[1]:
tags[1] = tags[1].split("_up")[0]+"_down"
if "_backup_up" in tags[2]:
tags[2] = tags[2].split("_up")[0]+"_down"
payload = {'tags': tags[1]+" "+tags[2]}
#Setzen der Tags
#Netzwerk wird von S3 Bucket gelöscht
s3.put_object(Body="", Bucket=bucket, Key=key)
print("Sleeping for 30s...")