iSt0ne's Notes

Puppet: route模块

本文介绍一个简单地route puppet模块,用来控制系统的路由信息,当你的网络很大时,有可能需要添加很多路由来与其他网段通信,此模块实现系统启动时自动添加路由功能。
github地址:https://github.com/ist0ne/puppet-route

##1、描述

本模块依赖puppetlabs-stdlib,实现系统路由管理。

##2、用法

为主机或网段添加路由:

1
2
3
4
$target_net = ['20.20.20.0/24', '10.20.0.0/16', '10.10.20.21']
route { $target_net:
gateway => '10.10.10.1',
}

为主机和网段删除路由:

1
2
3
4
5
$target_net_absent = ['10.10.20.51', '10.20.30.0/16']
route { $target_net_absent:
ensure => absent,
gateway => '10.10.10.1',
}

##3、模块代码解析

自定义facter,需要开启pluginsync自定义facter才能生效。

1
2
3
4
5
Facter.add("route") do
setcode do
Facter::Util::Resolution.exec('which route')
end
end

在route定义中通过${::route}引用自定义的facter。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
define route (
$ensure = present,
$gateway = '',
$route_file = 'S27route',
$route_file_path = '/etc/rc3.d'
) {
validate_re($ensure, [present, 'add', absent, 'del'])
validate_string($gateway)
validate_string($route_file)
validate_absolute_path($route_file_path)
# 判断$gateway变量,必须为IP地址
if ! is_ip_address($gateway) {
fail("The gateway must be a ipaddress.")
}
# 根据目标地址中是否包含“/”来判断是给网段还是给主机添加路由
if $name =~ /\// {
$target_type = 'net'
} else {
$target_type = 'host'
}
# 添加路由配置文件,用于开机自动添加路由
exec { "touch_route_file_$name":
command => "touch ${route_file_path}/${route_file}",
unless => "test -f ${route_file_path}/${route_file}",
}
# 添加路由并立即生效
if ($ensure in [present, 'add']) {
file_line { "$name":
ensure => present,
line => "${::route} add -${target_type} ${title} gw ${gateway}",
path => "${route_file_path}/${route_file}",
}
exec { "$name":
command => "${::route} add -${target_type} ${title} gw ${gateway}",
refreshonly => true,
subscribe => File_line[$name],
}
# 删除路由并立即生效
} elsif ($ensure in [absent, 'del']) {
file_line { "$name":
ensure => absent,
line => "${::route} add -${target_type} ${title} gw ${gateway}",
path => "${route_file_path}/${route_file}",
}
exec { "$name":
command => "${::route} del -${target_type} ${title} gw ${gateway}",
refreshonly => true,
subscribe => File_line[$name],
}
}
Exec["touch_route_file_$name"] -> File_line["$name"]
}