通过Boto3更新AWS中的路由表

时间:2017-02-17 17:33:05

标签: python amazon-web-services boto3

我是boto3的新手,我正在创建一个python脚本,它将收集来自亚马逊的IP地址列表,并将其与我们的一个路由表中的当前路由进行比较。

我首先收集所有使用CLOUDFRONT标记的IP。然后我需要检查路由表中的当前路由是否与此列表匹配。如果列表匹配,则无需更改任何内容。如果列表不匹配,则需要删除具有Internet网关目的地的路由,并且需要添加新列表,并且所有这些路由都将Internet网关作为目标。

这是我目前的代码:

def getCFIPs():
    #get json from amazon
    with urllib.request.urlopen('https://ip-ranges.amazonaws.com/ip-    ranges.json') as response:
        urlData=json.loads(response.read().decode('utf-8'))

    #debug output
    #print(json.dumps(urlData, indent=2))

    cfIPs=[]

    for entry in urlData['prefixes']:
        #print(json.dumps(entry, indent=2))
        if(entry['service'] == "CLOUDFRONT"):
            cfIPs.append(entry['ip_prefix'])

    #print(json.dumps(cfIPs, indent=2))

    return cfIPs

def updateRouteTables(account, tableId, gateId, desCidrBlock):
    #keep local, vgw route, and pl route
    #if routes match: keep the Same
    #if not match: delete old igw routes & add new ones

    #Connect to EC2
    ec2=boto3.client('ec2')

    #compare routes in route table with cfIPs (only with destination IGW)
    #if IGW routes match cfIPs, print "lists match"

    #if IGW routes do not match cfIPs, delete all routes with destination IGW
    delete_route(tableId, desCidrBlock, dry_run=False)

    #add routes in cfIPs to destination IGW if not matching
    ec2=client.create_route(
        DryRun=True|False,
        RouteTableId=tableId,
        DestinationCidrBlock='string',
        #InternetGateway - Search for GatewayID
        GatewayId=gateId,
        InstanceId='string',
        NetworkInterfaceId='string',
        VpcPeeringConnectionId='string'
    )

if __name__ == '__main__':

    cfIPs=getCFIPs()

    account = sys.argv[1]
    tableId = sys.argv[2]
    gateId = sys.argv[3]
    desCidrBlock = sys.argv[4]

    updateRouteTables(account, tableId, gateId, desCidrBlock)

    with open(repoRootDir + "\PythonUtils\AccountRoleInfo.json") as data_file:
        accounts = json.load(data_file)

    for account in accounts:
        print("Running Cloudfront Update Scan in Account: " + account)

        updateRouteTables(account, tableId, gateId, desCidrBlock)

我不确定如何使用Internet Gateway的目标获取updateRouteTables()中的当前路由,并将它们与我从getCFIPs()获得的列表进行比较。我也不确定我的delete_route和create_route代码是否正确。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这是示例代码。我要匹配接口列表,因为我需要删除网关为NetworkInterfaceId(如果存在)的路由并添加新路由

def update_route_table(self):
        client = boto3.client('ec2',self.region,config=self.retry_config)
        resp_rt_table = client.describe_route_tables(Filters=[{'Name': 'vpc-id','Values': [self.vpc_id,]},])['RouteTables']
        interface_mapping=self.merge_peer_self_eni_dict() 
        for key in interface_mapping.keys(): 
            for iter in resp_rt_table: 
                for each_route in  iter['Routes']: 
                    try:
                        if each_route['NetworkInterfaceId'] == key:
                            try:
                                client.delete_route(DestinationCidrBlock=each_route['DestinationCidrBlock'],RouteTableId=iter['RouteTableId'])
                                print "Route Deleted for "+str(each_route['DestinationCidrBlock'])+" with eniid "+str(key)
                                client.create_route(DestinationCidrBlock=each_route['DestinationCidrBlock'],NetworkInterfaceId=interface_mapping[key],RouteTableId=iter['RouteTableId'])
                                print "Route created for  "+str(each_route['DestinationCidrBlock'])+" with eniid "+str(interface_mapping[key])
                            except Exception as e:
                                print e
                    except :
                        continue