今天写一个Openstack4J API操作浮动IP的例子。
首先看看有哪些浮动IP池:
代码:
OSClientV3 os = OSFactory.builderV3().endpoint("http://10.0.0.11:5000/v3")
.credentials("zph", "123456", Identifier.byName("default"))
List<String> pools = os.compute().floatingIps().getPoolNames();
System.out.println(pools);
输出:
[ext_zwn]
事实上就是只有一个浮动ip池
现在我们来给一台实例添加浮动ip地址,分两种情况
第一种情况是没有装Neutron的
我现在有这样一台实例
注意到这台实例的标识是:11e44f47-d802-425c-8f6e-825eb751d070
他的固定IP是: 192.168.10.46
代码如下:
OSClientV3 os = OSFactory.builderV3().endpoint("http://10.0.0.11:5000/v3")
.credentials("zph", "123456", Identifier.byName("default"))
.scopeToProject(Identifier.byId("7e0ba2f4b7e74f0eb21fec7642d42544")).authenticate();
FloatingIP ip = os.compute().floatingIps().allocateIP("ext_zwn");//从上面查出来的浮动IP池中分配分配一个浮动ip地址
System.out.println(ip);//看看分配的这个浮动IP长什么样子。
ActionResponse r = os.compute().floatingIps().addFloatingIP(
os.compute().servers().get("11e44f47-d802-425c-8f6e-825eb751d070"), "192.168.10.46",
ip.getFloatingIpAddress());
System.out.println(r);
这里说一下这个:
ActionResponse r = os.compute().floatingIps().addFloatingIP(
os.compute().servers().get("11e44f47-d802-425c-8f6e-825eb751d070"), "192.168.10.46",ip.getFloatingIpAddress());
他的原型是这样:
ActionResponse r = os.compute().floatingIps().addFloatingIP(
os.compute().servers().get("11e44f47-d802-425c-8f6e-825eb751d070"), "192.168.10.46",ip.getFloatingIpAddress());
第一个参数是把server传进去,我通过os.compute().servers().get()传入刚刚上面的那个实例的标识号拿到要分配浮动IP的Server
第二个参数就是固定的IP地址。
第三个是刚刚通过FloatingIP ip = os.compute().floatingIps().allocateIP(“ext_zwn”);返回的浮动IP地址
执行结果:
看到了吗 这里成功添加上了浮动IP
如果你装了Neutron的话分配浮动IP会更加方便:
FloatingIP ip = os.compute().floatingIps().allocateIP("ext_zwn");
NetFloatingIP netFloatingIP = os.networking().floatingip().get(ip.getId());
Server server = os.compute().servers().get("11e44f47-d802-425c-8f6e-825eb751d070");
ActionResponse r = os.compute().floatingIps().addFloatingIP(server, netFloatingIP.getFloatingIpAddress());
System.out.println(r);
取消关联浮动IP:
ActionResponse r = os.compute().floatingIps().removeFloatingIP(server, "浮动IP地址");
结束~