实现 OpenStack Neutron 路由模式

1. 整体流程

下面是实现 OpenStack Neutron 路由模式的整体流程:

步骤 描述
1. 创建网络 创建网络用于连接虚拟机
2. 创建子网 创建子网用于分配 IP 地址
3. 创建路由器 创建路由器用于连接不同的网络
4. 绑定网关 将路由器绑定到外部网络
5. 创建端口 创建端口用于连接虚拟机
6. 创建安全组规则 创建安全组规则用于控制流量
7. 关联子网和路由器 将子网关联到路由器
8. 配置虚拟机网关 配置虚拟机的默认网关为路由器
9. 配置虚拟机 IP 地址 配置虚拟机的 IP 地址

2. 代码实现

2.1. 创建网络

引用形式的描述信息:创建网络
from neutronclient.v2_0 import client

def create_network(network_name):
    neutron = client.Client(auth_url=auth_url, username=username, password=password, project_name=project_name)
    network = neutron.create_network({'network': {'name': network_name}})
    return network

network = create_network('my_network')

上述代码会创建一个名为 "my_network" 的网络。

2.2. 创建子网

引用形式的描述信息:创建子网
from neutronclient.v2_0 import client

def create_subnet(network_id, subnet_name, cidr):
    neutron = client.Client(auth_url=auth_url, username=username, password=password, project_name=project_name)
    subnet = neutron.create_subnet({'subnet': {'network_id': network_id, 'name': subnet_name, 'cidr': cidr}})
    return subnet

subnet = create_subnet(network['id'], 'my_subnet', '192.168.0.0/24')

上述代码会在之前创建的网络上创建一个名为 "my_subnet" 的子网。

2.3. 创建路由器

引用形式的描述信息:创建路由器
from neutronclient.v2_0 import client

def create_router(router_name):
    neutron = client.Client(auth_url=auth_url, username=username, password=password, project_name=project_name)
    router = neutron.create_router({'router': {'name': router_name}})
    return router

router = create_router('my_router')

上述代码会创建一个名为 "my_router" 的路由器。

2.4. 绑定网关

引用形式的描述信息:绑定网关
from neutronclient.v2_0 import client

def set_gateway(router_id, external_network_id):
    neutron = client.Client(auth_url=auth_url, username=username, password=password, project_name=project_name)
    neutron.add_gateway_router(router_id, {'network_id': external_network_id})

set_gateway(router['id'], external_network['id'])

上述代码会将之前创建的路由器绑定到外部网络。

2.5. 创建端口

引用形式的描述信息:创建端口
from neutronclient.v2_0 import client

def create_port(network_id, port_name):
    neutron = client.Client(auth_url=auth_url, username=username, password=password, project_name=project_name)
    port = neutron.create_port({'port': {'network_id': network_id, 'name': port_name}})
    return port

port = create_port(network['id'], 'my_port')

上述代码会创建一个名为 "my_port" 的端口,并将其连接到之前创建的网络。

2.6. 创建安全组规则

引用形式的描述信息:创建安全组规则
from neutronclient.v2_0 import client

def create_security_group_rule(security_group_id, direction, protocol, port_range_min, port_range_max):
    neutron = client.Client(auth_url=auth_url, username=username, password=password, project_name=project_name)
    security_group_rule = neutron.create_security_group_rule({'security_group_rule': {'security_group_id': security_group_id, 'direction': direction, 'protocol': protocol, 'port_range_min': port_range_min, 'port_range_max': port_range_max}})
    return security_group_rule

security_group_rule = create_security_group_rule(security_group['id'], 'ingress', 'tcp