上一篇文章简单介绍了一下puppet和puppet的资源,今天来说一下puppet的变量和puppet的流程控制语句;
数据类型:
字符型:引号可有可无;但单引号为强引用,双引号为弱引用;
数值型:默认均识别为字符串,仅在数值上下文才以数值对待;
数组:[]中以逗号分隔元素列表;
布尔型值:true, false;
undef:未定义;相当于unset;
hash:{}中以逗号分隔k/v数据列表;key只能是字符型,value可以任意类型;
正则表达式:
(?:) :启用的选项
(?-:):禁用的选项
正则options:
i:忽略字符大小写;
m:把.当做换行符,一般禁用;
x:忽略<PATTERN>模式匹配中的空白字符;
常用:(?i-mx:PATTERN)====》其中-表示不启用mx功能
hash eg:
{ 'mon' => 'Monday',
'tue' => 'Tuesday',
}
注意:正则表达式不能赋值给变量,仅用在接收=~或者!~操作符的位置;
变量定义或者引用时都要加上‘$’;
1、facts:节点级变量,由facter提供;top scope;
2、内建变量:
2.1)、master端变量 : $servername, $serverip, $serverversion
2.2)、agent端变量 :$clientcert, $clientversion, $environment
2.3)、parser变量:$module_name
3、用户自定义变量:
Top scope:顶级作用域;
Node scope:节点作用域;
Class scope:类作用域;
作用域越小优先级越高;
引用父级域中的变量时:$node_scopename::class_scopname::varname
顶级域名一般为空;所以引用顶级域中的变量时时:$::varname
1、单分支if语句:
if CONDITION {
...
}
2、双分支if语句:
if CONDITION {
...
} else {
...
}
3、多分支if语句:
if CONDITION {
...
} elsif CONDITION {
...
}else {
...
}
CONDITION的给定方式:
(1) 变量
(2) 比较表达式
(3) 有返回值的函数
eg:
if $osfamily =~ /(?i-mx:debian)/ {
$webserver = 'apache2'
} else {
$webserver = 'httpd'
}
package{"$webserver":
ensure => installed,
before => [ File['httpd.conf'], Service['httpd'] ],
}
file{'httpd.conf':
path => '/etc/httpd/conf/httpd.conf',
source => '/root/manifests/httpd.conf',
ensure => file,
}
service{'httpd':
ensure => running,
enable => true,
restart => 'systemctl restart httpd.service',
subscribe => File['httpd.conf'],
}
语法:
case CONTROL_EXPRESSION {
case1: { ... }
case2: { ... }
case3: { ... }
...
default: { ... }
}
CONTROL_EXPRESSION:
(1) 变量
(2) 表达式
(3) 有返回值的函数各case的给定方式:
(1) 直接字串;
(2) 变量
(3) 有返回值的函数
(4) 正则表达式模式;
(5) default
case $osfamily {
"RedHat": { $webserver='httpd' }
/(?i-mx:debian)/: { $webserver='apache2' }
default: { $webserver='httpd' }
}
package{"$webserver":
ensure => installed,
before => [ File['httpd.conf'], Service['httpd'] ],
}
file{'httpd.conf':
path => '/etc/httpd/conf/httpd.conf',
source => '/root/manifests/httpd.conf',
ensure => file,
}
service{'httpd':
ensure => running,
enable => true,
restart => 'systemctl restart httpd.service',
subscribe => File['httpd.conf'],
}
和case语法类似,但是不执行代码块,直接返回值value;
语法:
CONTROL_VARIABLE ? {
case1 => value1,
case2 => value2,
...
default => valueN,
}
CONTROL_VARIABLE的给定方法:
(1) 变量
(2) 有返回值的函数
各case的给定方式:
(1) 直接字串;
(2) 变量
(3) 有返回值的函数
(4) 正则表达式模式;
(5) default
$webserver = $osfamily ? {
"Redhat" => 'httpd',
/(?i-mx:debian)/ => 'apache2',
default => 'httpd',
}
package{"$webserver":
ensure => installed,
before => [ File['httpd.conf'], Service['httpd'] ],
}
file{'httpd.conf':
path => '/etc/httpd/conf/httpd.conf',
source => '/root/manifests/httpd.conf',
ensure => file,
}
service{'httpd':
ensure => running,
enable => true,
restart => 'systemctl restart httpd.service',
subscribe => File['httpd.conf'],
}