自動化運維工具之Puppet變數、正規表示式、流程控制、類和模板

1874發表於2020-12-03

  前文我們瞭解了puppet的file、exec、cron、notify這四種核心資源型別的使用以及資源見定義通知/訂閱關係,回顧請參考https://www.cnblogs.com/qiuhom-1874/p/14073437.html;今天我們來了解下puppet中的變數、正規表示式和條件判斷的相關話題;

  puppet中的變數

  在puppet中變數的定義和使用都是要加“$”,比如定義變數$webserver=nginx;則表示把nginx這個字串複製給$webserver這個變數;引用變數直接使用$webserver即可;在puppet中賦值操作符為“=”,表示把等號右邊邊的值賦給左邊的變數,任何正常資料型別(非正則)的值都可以賦予puppet中的變數,比如字串、數值、布林值、陣列、hash以及特殊的undef值(即變數未賦值);

  puppet中的資料型別

    字元型:非結構化的文字字串,可以使用引號,也可以不使用引號;單引號表示強引用,雙引號表示弱引用;所謂強引用表示變數不會替換,弱引用表示能夠進行變數替換;字元型值是支援用轉義符;

    數字型:可為整數或浮點數,不過,puppet只有在數值上下文才把數值當作數值型對待,其他情況一律以字元型處理;比如進行加減乘除等運算時,它會把數值型值當作數值進行計算;

    陣列:陣列值為中括號“[]”中的以逗號分隔的專案列表,最後一個專案後面可以沒有逗號;陣列中的元素可以為任意可用資料型別,包括hash或其他陣列,陣列中的元素為陣列,我們把這樣的陣列叫多維陣列;陣列的索引為從0開始的整數,也可以使用負數索引;

    布林型:true和false,不能加任何引號;if語句的測試條件和比較表示式都會返回布林型值,另外,其他資料型別也可以自動轉換為布林型值,如字串,空串為false,非空則true;數值型就是0為false,非0為true等等;

    undef:從未被宣告的變數的值型別即為undef;也可手動為某變數賦予undef值,即直接使用不加引號的undef字串;有點類似shell中的unset;

    hash:即為外來鍵值資料型別,鍵和值之間使用“=>”分隔,鍵值對定義在“{}”中,彼此間以逗號分隔;其鍵為字元型資料,而值可以為puppet中支援的任意資料型別;訪問hash型別的資料元素要使用“鍵”當作索引進行訪問;

  puppet中變數作用域

  提示:所謂變數作用域表示變數的使用生效的範圍,在puppet中作用域可用於限定變數及資源預設屬性的作用範圍;但不能用於限定資源名稱及資源引用的生效範圍;任何給定的scope都可以訪問它自己的內容,以及接收來自於其父scope、節點scope以及top scope的內容;簡單講就是作用域小的可以引用作用域大的變數,也可以更改作用域大的變數的值;但是作用域大的不能操作作用域小的變數;如上圖所示,top scope僅能訪問直接的變數和屬性預設值;node scope能訪問自己的及top scope的變數和屬性預設值;example::parent,example::other和example::four能訪問自己的以及節點scope和top scope的變數和預設值;如果要訪問非當前scope中的變數,則需要通過完全限制名稱進行;如$vhostdir=$apache::params::vhostdir;這裡需要注意一點,如果top scope的名稱為空,如要引用其變數可以使用類似$::sofamily的方式進行引用;

  puppet中的內建變數

  在puppet中變數來源可以從facter,agent,master,直譯器以及使用者自定義的變數;其中facter是一個工具,它可以收集系統資訊,規範化之後存放在一系列變數中,並傳遞給puppet;facter的各變數是top scope的變數,這意味著,可以在各個manifest中直接通過${fact name}訪問所需的fact變數;檢視系統fact變數有哪些,可以使用facter -p輸出fact變數;agent端的變數常用的有$environment這表示agent端的環境變數,$clientcert表示agent端的證照;$clientversion表示agent puppet的版本資訊;master 端常用變數有$servername,該變數表示服務端名稱;$serverip服務端ip,$serverversion服務端puppet的版本資訊;直譯器中的變數$module_name表示正在執行的模組名稱;這裡需要注意agent和master的內建變數只有在master/agent這種模型中才有效,單機模型無效;

  puppet中常用的操作符

操作符 描述 操作符 描述 操作符 描述
== 等於 =~ 正則模式匹配 +
!= 不等於 !~ 正則模式不匹配 -
< 小於 in 成員關係判定 *
> 大於 and /
<= 小於等於 or << 左移位
>= 大於等於 ! >> 右移位

 

 

 

 

 

 

 

 

 

  puppet中的正規表示式

  正規表示式在puppet中屬於非標準的資料型別,不能賦值給變數,僅能用於有限的幾個接受正規表示式的地方使用,即接受使用“=~”或“!~”匹配操作符的位置,通常包含case語句中的selector,以及節點名稱匹配的位置;它不能傳遞給函式或用於資源屬性定義;

  puppet中正規表示式的兩個特殊使用方式

  (?<ENABLED OPTION>:<PATTERN>)和(?-<DISABLED OPTION>:<PATTERN>),其中OPTIONS有i,m,x,其中i表示忽略字元大小寫;m表示把“.”點號當作換行符;x表示忽略<PATTERN>中的空白字元;比如(?imx:PATTENR)就表示忽略字元大小寫,把PATTERN中的點號當作換行符,並且忽略其中的空白字元;(?i-mx:PATTERN)表示忽略字元大小寫,不把pattern中的點號當換行符,也不忽略pattern中的空白字元;

  puppet中的流程控制

  所謂流程控制就是在puppet程式碼中加入了條件控制語句,如if語句,case語句,selector語句,只有滿足了條件才會執行對應的程式碼;if語句語法如下

  單分支

if  CONDITION {
    ...
}

  雙分支

if  CONDITION {
    ...
} else {
    ...
}

  多分支

if  CONDITION {
    ...
} elsif {
    ...
} else{
    ...
}

  提示:條件可以是變數,比較表示式或有返回值的函式;

  示例:通過判斷不同作業系統來安裝apache

[root@node12 ~]# cat if.pp
if $operatingsystem == "CentOS" {
        $webserver = "httpd"
}elsif $operatingsystem == "Ubuntu" {
        $webserver = "apache2"
}else{
        $webserver = "apahce"
}

package{"$webserver":
        ensure  => installed,
}
[root@node12 ~]# 

  提示:以上資源清單表示,通過判斷$operatingsystem這個變數的值來賦值$webserver的值;如果對應$operatingsystem的值為CentOS,則$webserver的值就為httpd,如果是Ubuntu $webserver的值就為apache2,如果前兩個條件都不滿足,則$webserver的值為apache;然後通過$webserver這個變數的值來安裝包;

  應用資源清單

[root@node12 ~]# puppet apply -v --noop if.pp
Notice: Compiled catalog for node12.test.org in environment production in 0.65 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1606994860'
Notice: /Stage[main]/Main/Package[httpd]/ensure: current_value absent, should be present (noop)
Notice: Class[Main]: Would have triggered 'refresh' from 1 events
Notice: Stage[main]: Would have triggered 'refresh' from 1 events
Notice: Finished catalog run in 1.24 seconds
[root@node12 ~]# puppet apply -v  if.pp      
Notice: Compiled catalog for node12.test.org in environment production in 0.18 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1606994891'
Notice: /Stage[main]/Main/Package[httpd]/ensure: created
Notice: Finished catalog run in 7.99 seconds
[root@node12 ~]# 

  提示:從上述資訊中可以看到,當前安裝的包上httpd;原因是本機是一個centos系統;$operatingsystem這個變數是一個fact變數,主要儲存作業系統名稱;

  示例:if語句中使用正規表示式

[root@node12 ~]# cat if.pp
if $operatingsystem =~/(?i-mx:(centos|redhat))/{
        $webserver = "httpd"
}elsif $operatingsystem =~ /(?i-mx:(ubuntu|debian))/{
        $webserver = "apache2"
}else{
        $webserver = "apahce"
}

package{"$webserver":
        ensure  => installed,
}
[root@node12 ~]# 

  提示:使用正規表示式需要將正規表示式寫在“//”之間;

  解除安裝httpd,應用資源清單

[root@node12 ~]# rpm -e httpd
[root@node12 ~]# puppet apply -v  if.pp
Notice: Compiled catalog for node12.test.org in environment production in 0.18 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1606995583'
Notice: /Stage[main]/Main/Package[httpd]/ensure: created
Notice: Finished catalog run in 1.86 seconds
[root@node12 ~]# 

  提示:可以看到應用清單並沒有報錯,提示httpd已經建立;

  puppet中的case語句

  語法

case CONTROL_EXPRESSION {
    case1: { ... }
    case2: { ... }
    case3: { ... }
    ...
    default: { ... }
}

  提示:case語句和if語句的作用是類似的,case語句會從多個程式碼塊中選擇一個分支執行,只要其中任意一個case的值滿足對應的控制表示式,就執行對應case後面的程式碼塊,然後退出;如果所有case都不滿足,則執行default對應的程式碼塊;這裡的控制表示式可以是變數,可以是比較表示式,也可以是有返回值的函式;case可以是字串,正規表示式,變數,有返回值的函式和default;

  示例

[root@node12 ~]# cat case.pp
case $osfamily {
        "RedHat":{ $webserver="httpd" }
        /(?i-mx:debian)/:{ $webserver="apache2" }
        default:{ $webserver="apache" }
}

package{"$webserver":
        ensure  => installed,
}
[root@node12 ~]# 

  解除安裝httpd,執行資源清單,看看httpd是否會被安裝?

[root@node12 ~]# rpm -e httpd
[root@node12 ~]# puppet apply -v  case.pp 
Notice: Compiled catalog for node12.test.org in environment production in 0.18 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1606996150'
Notice: /Stage[main]/Main/Package[httpd]/ensure: created
Notice: Finished catalog run in 1.82 seconds
[root@node12 ~]# rpm -q httpd
httpd-2.4.6-97.el7.centos.x86_64
[root@node12 ~]# 

  提示:可以看到httpd可以正常的安裝;

  selector語句

  語法

CONTROL_VARIABLE ? {
    case1 => value1,
    case2 => value2,
    ...
    default => valueN,
}

  提示:整個selector語句會被當作一個單獨的值,puppet會將控制變數按列出的次序依次與每個case進行比較,並在遇到一個匹配的case後,將其值作為整個語句的值進行返回,並忽略後面的其他case;控制變數與各case比較的方式和case語句相同,但如果沒有任何一個case與控制變數匹配,puppet在編譯時將報錯,因此,我們在使用selector必須提供一個default case;控制變數只能是一個變數或一個有返回值的函式,不能使用表示式;各個case的值可以是字串,變數,有返回值的函式,正規表示式或default;

  示例

[root@node12 ~]# cat selector.pp
$pkgname = $operatingsystem ? {
        /(?i-mx:(ubuntu|debian))/       => 'apache2',
        /(?i-mx:(redhat|fedora|centos))/        => 'httpd',
        default => 'apache',
}
package{"$pkgname":
        ensure  => installed,
}
[root@node12 ~]# 

  解除安裝httpd,應用資源清單

[root@node12 ~]# rpm -e httpd
[root@node12 ~]# puppet apply -v --noop selector.pp
Notice: Compiled catalog for node12.test.org in environment production in 0.18 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1606997882'
Notice: /Stage[main]/Main/Package[httpd]/ensure: current_value absent, should be present (noop)
Notice: Class[Main]: Would have triggered 'refresh' from 1 events
Notice: Stage[main]: Would have triggered 'refresh' from 1 events
Notice: Finished catalog run in 0.08 seconds
[root@node12 ~]# puppet apply -v  selector.pp      
Notice: Compiled catalog for node12.test.org in environment production in 0.18 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1606997889'
Notice: /Stage[main]/Main/Package[httpd]/ensure: created
Notice: Finished catalog run in 1.96 seconds
[root@node12 ~]# rpm -q httpd
httpd-2.4.6-97.el7.centos.x86_64
[root@node12 ~]# 

  提示:可以看到httpd通過使用selector的方式定義的資源清單一樣可以正常安裝;

  puppet中的類

  類是用於同於目標的一組資源,因此,它是命名的程式碼塊,在某一個位置建立之後可在puppet全域性使用;puppet中的類和其他程式語言中的類的功能很類似,puppet中的類可被繼承,也可以有子類;

  類的定義語法

class class_name($var1=value1,$var2=value2){
    ... puppet code ...
}

  提示:class是關鍵字,class_name是類名,類名只能以小寫字母開頭,可以包含小寫字母,數字,下劃線;小括號裡是定義類的形參,每個形參可以有預設值,也可以沒有,多個形參用逗號隔開;大括號裡寫puppet的程式碼;

  示例:定義一個apache的類

[root@node12 ~]# cat apache.pp
class apache {
        package{"httpd":
                ensure  => installed,
        }
        service{"httpd":
                ensure  => running,
        }
}
[root@node12 ~]# 

  提示:以上清單中定義了一個apache的類,主要完成了安裝包和啟動服務;這裡需要注意一點,類定義好以後,如果我們不宣告類,則它不會執行,有點類似函式一樣,要向讓類執行,我們需要宣告類;

  在puppet中類的宣告常用的方式有兩種,第一種是使用include關鍵字+類名;第二種是類似定義資源一樣來宣告類,其中資源型別為class,title必須為類名,這種方式通常用於有引數的類的宣告;

  示例:使用include關鍵字+類名宣告類

[root@node12 ~]# cat apache.pp
class apache {
        package{"httpd":
                ensure  => installed,
        }
        service{"httpd":
                ensure  => running,
        }
}

include apache

[root@node12 ~]# 

  執行清單

[root@node12 ~]# ss -tnl
State      Recv-Q Send-Q         Local Address:Port                        Peer Address:Port              
LISTEN     0      128                        *:26379                                  *:*                  
LISTEN     0      128                        *:22                                     *:*                  
LISTEN     0      100                127.0.0.1:25                                     *:*                  
LISTEN     0      128                        *:27017                                  *:*                  
LISTEN     0      128                       :::22                                    :::*                  
LISTEN     0      100                      ::1:25                                    :::*                  
[root@node12 ~]# puppet apply -v --noop apache.pp 
Notice: Compiled catalog for node12.test.org in environment production in 0.26 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1607005266'
Notice: /Stage[main]/Apache/Service[httpd]/ensure: current_value stopped, should be running (noop)
Info: /Stage[main]/Apache/Service[httpd]: Unscheduling refresh on Service[httpd]
Notice: Class[Apache]: Would have triggered 'refresh' from 1 events
Notice: Stage[main]: Would have triggered 'refresh' from 1 events
Notice: Finished catalog run in 0.13 seconds
[root@node12 ~]# puppet apply -v  apache.pp       
Notice: Compiled catalog for node12.test.org in environment production in 0.27 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1607005272'
Notice: /Stage[main]/Apache/Service[httpd]/ensure: ensure changed 'stopped' to 'running'
Info: /Stage[main]/Apache/Service[httpd]: Unscheduling refresh on Service[httpd]
Notice: Finished catalog run in 0.22 seconds
[root@node12 ~]# ss -tnl
State      Recv-Q Send-Q         Local Address:Port                        Peer Address:Port              
LISTEN     0      128                        *:26379                                  *:*                  
LISTEN     0      128                        *:22                                     *:*                  
LISTEN     0      100                127.0.0.1:25                                     *:*                  
LISTEN     0      128                        *:27017                                  *:*                  
LISTEN     0      128                       :::80                                    :::*                  
LISTEN     0      128                       :::22                                    :::*                  
LISTEN     0      100                      ::1:25                                    :::*                  
[root@node12 ~]# 

  提示:可以看到httpd服務已經啟動;

  示例:定義帶參類

[root@node12 ~]# cat class1.pp
class dbserver ($pkg='mariadb-server',$svr='mariadb'){
        package{"$pkg":
                ensure  => latest,
        }
        service{"$svr":
                ensure  => running,
                enable  => true,
        }
}

if $operatingsystem == "CentOS" or $operatingsystem == "RedHat"{
        case $operatingsystemmajrelease {
                '7': { $pkgname='mariadb-server' $svrname='mariadb' }
                default: { $pkgname='mysql-server' $svrname='mysqld' }
        }
}

class{"dbserver":
        pkg     => $pkgname,
        svr     => $svrname,
}
[root@node12 ~]# 

  提示:以上清單主要完成對於不同版本的centos,安裝和啟動不同的服務;在centos7上安裝mariadb-server,啟動mariadb服務;其他版本的centos安裝mysql-server,啟動mysqld服務;這裡需要注意一點,宣告類中的行參不能帶$,我們可以理解為行參就是類的一個屬性;

  執行清單

[root@node12 ~]# ss -tnl
State      Recv-Q Send-Q         Local Address:Port                        Peer Address:Port              
LISTEN     0      128                        *:26379                                  *:*                  
LISTEN     0      128                        *:22                                     *:*                  
LISTEN     0      100                127.0.0.1:25                                     *:*                  
LISTEN     0      128                        *:27017                                  *:*                  
LISTEN     0      128                       :::80                                    :::*                  
LISTEN     0      128                       :::22                                    :::*                  
LISTEN     0      100                      ::1:25                                    :::*                  
[root@node12 ~]# puppet apply -v --noop class1.pp 
Notice: Compiled catalog for node12.test.org in environment production in 0.27 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1607007562'
Notice: /Stage[main]/Dbserver/Service[mariadb]/ensure: current_value stopped, should be running (noop)
Info: /Stage[main]/Dbserver/Service[mariadb]: Unscheduling refresh on Service[mariadb]
Notice: Class[Dbserver]: Would have triggered 'refresh' from 1 events
Notice: Stage[main]: Would have triggered 'refresh' from 1 events
Notice: Finished catalog run in 0.47 seconds
[root@node12 ~]# puppet apply -v  class1.pp       
Notice: Compiled catalog for node12.test.org in environment production in 0.27 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1607007569'
Notice: /Stage[main]/Dbserver/Service[mariadb]/ensure: ensure changed 'stopped' to 'running'
Info: /Stage[main]/Dbserver/Service[mariadb]: Unscheduling refresh on Service[mariadb]
Notice: Finished catalog run in 2.76 seconds
[root@node12 ~]# ss -tnl
State      Recv-Q Send-Q         Local Address:Port                        Peer Address:Port              
LISTEN     0      128                        *:26379                                  *:*                  
LISTEN     0      128                        *:22                                     *:*                  
LISTEN     0      100                127.0.0.1:25                                     *:*                  
LISTEN     0      128                        *:27017                                  *:*                  
LISTEN     0      50                         *:3306                                   *:*                  
LISTEN     0      128                       :::80                                    :::*                  
LISTEN     0      128                       :::22                                    :::*                  
LISTEN     0      100                      ::1:25                                    :::*                  
[root@node12 ~]# systemctl is-enabled mariadb.service 
enabled
[root@node12 ~]# 

  提示:可以看到在當前系統上執行清單,啟動了mariadb;

  類的繼承

  類的繼承是子類繼承父類中的所有功能程式碼,它可以對父類中的所有屬性進行修改,其定義語法如下

class childer_class_name inherits parent_class_name{
    ...puppet code ...
}

  提示:子類名稱需使用完全限定名稱,比如父類是apache,子類名可以寫成apache::web;類似這種;inherits是關鍵字表示繼承之意,後面加父類名稱;

  示例

[root@node12 ~]# cat redis.pp
class redis{
        package{"redis":
                ensure  => installed,
        }
        service{"redis":
                ensure  => running,
                enable  => true,
                hasrestart      => true,
                restart => 'service redis restart',
        }
}

class redis::master inherits redis {
        file{"/etc/redis.conf":
                ensure  => file,
                source  => '/root/redis-master.conf',
        }
        Service["redis"]{
                subscribe       => File["/etc/redis.conf"],
                restart => 'systemctl restart redis'
        }
}

include redis::master
[root@node12 ~]# 

  提示:以上清單定義了兩個類,一個是父類名為reids,另一個為子類名為redis::master;子類繼承父類,並在其基礎上新增了file資源以及增加了service資源的訂閱關係;

  本地redis-master.conf配置檔案內容

[root@node12 ~]# cat /root/redis-master.conf 
bind 0.0.0.0
protected-mode yes
port 6379
tcp-backlog 511
timeout 0
tcp-keepalive 300
daemonize no
supervised no
pidfile /var/run/redis_6379.pid
loglevel notice
logfile /var/log/redis/redis.log
databases 16
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /var/lib/redis
slave-serve-stale-data yes
slave-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
slave-priority 100
appendonly no
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
aof-rewrite-incremental-fsync yes
[root@node12 ~]# 

  執行清單,看看redis是否會監聽在本機所有地址的6379埠?

[root@node12 ~]# ss -tnl
State       Recv-Q Send-Q       Local Address:Port                      Peer Address:Port              
LISTEN      0      128                      *:22                                   *:*                  
LISTEN      0      100              127.0.0.1:25                                   *:*                  
LISTEN      0      128                      *:27017                                *:*                  
LISTEN      0      50                       *:3306                                 *:*                  
LISTEN      0      128                     :::80                                  :::*                  
LISTEN      0      128                     :::22                                  :::*                  
LISTEN      0      100                    ::1:25                                  :::*                  
[root@node12 ~]# puppet apply -v --noop redis.pp 
Notice: Compiled catalog for node12.test.org in environment production in 0.32 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1607008817'
Notice: /Stage[main]/Redis::Master/File[/etc/redis.conf]/content: current_value {md5}cb9ab7d298a50a0de20077de143e3f73, should be {md5}12e59b058c0ef61ad52bcfa2d4de58ff (noop)
Info: /Stage[main]/Redis::Master/File[/etc/redis.conf]: Scheduling refresh of Service[redis]
Notice: Class[Redis::Master]: Would have triggered 'refresh' from 1 events
Notice: /Stage[main]/Redis/Service[redis]/ensure: current_value stopped, should be running (noop)
Info: /Stage[main]/Redis/Service[redis]: Unscheduling refresh on Service[redis]
Notice: Class[Redis]: Would have triggered 'refresh' from 1 events
Notice: Stage[main]: Would have triggered 'refresh' from 2 events
Notice: Finished catalog run in 0.18 seconds
[root@node12 ~]# puppet apply -v  redis.pp       
Notice: Compiled catalog for node12.test.org in environment production in 0.33 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1607008824'
Info: /Stage[main]/Redis::Master/File[/etc/redis.conf]: Filebucketed /etc/redis.conf to puppet with sum cb9ab7d298a50a0de20077de143e3f73
Notice: /Stage[main]/Redis::Master/File[/etc/redis.conf]/content: content changed '{md5}cb9ab7d298a50a0de20077de143e3f73' to '{md5}12e59b058c0ef61ad52bcfa2d4de58ff'
Info: /Stage[main]/Redis::Master/File[/etc/redis.conf]: Scheduling refresh of Service[redis]
Notice: /Stage[main]/Redis/Service[redis]/ensure: ensure changed 'stopped' to 'running'
Info: /Stage[main]/Redis/Service[redis]: Unscheduling refresh on Service[redis]
Notice: Finished catalog run in 0.13 seconds
[root@node12 ~]# ss -tnl
State       Recv-Q Send-Q       Local Address:Port                      Peer Address:Port              
LISTEN      0      128                      *:6379                                 *:*                  
LISTEN      0      128                      *:22                                   *:*                  
LISTEN      0      100              127.0.0.1:25                                   *:*                  
LISTEN      0      128                      *:27017                                *:*                  
LISTEN      0      50                       *:3306                                 *:*                  
LISTEN      0      128                     :::80                                  :::*                  
LISTEN      0      128                     :::22                                  :::*                  
LISTEN      0      100                    ::1:25                                  :::*                  
[root@node12 ~]# 

  提示:可以看到redis監聽在本機任何地址的6379埠;

  模板

  puppet中的模板和ansible中的模板功能很類似,主要用在為一些服務提供配置檔案模板,不同於ansible中的模板,puppet中的模板使用的erb模板語言,ansible使用的是jinja2模板語言;在puppet中使用模板的語法如下

file{'title':
    ensure	=> file,
    content	=> template('/PATH/TO/ERB_FILE'),
}

  提示:在複製配置檔案時,指定源需使用content來指定,並且呼叫內建函式template來指定要複製的原始檔,通常這個原始檔就是一個模板配置檔案;

  在模板檔案中使用內嵌的變數替換機制,其語法如下

<%= @VARIABLE_NAME %>

  提示:我們需要把要替換的值用上述變數的方式代替即可;

  示例:替換redis監聽地址

[root@node12 ~]# grep ^bind redis-master.conf.erb
bind <%= @ipaddress %>
[root@node12 ~]# 

  提示:以上內容表示bind 後面的值為ipaddress這個變數的值;這個變數是fact變數,主要用於存放本機ip地址;

  定義資源清單

[root@node12 ~]# cat redis.pp
class redis{
        package{"redis":
                ensure  => installed,
        }
        service{"redis":
                ensure  => running,
                enable  => true,
                hasrestart      => true,
                restart => 'service redis restart',
        }
}

class redis::master inherits redis {
        file{"/etc/redis.conf":
                ensure  => file,
                content => template('/root/redis-master.conf.erb'),
        }
        Service["redis"]{
                subscribe       => File["/etc/redis.conf"],
                restart => 'systemctl restart redis'
        }
}

include redis::master
[root@node12 ~]# 

  提示:以上清單在定義配置檔案原始檔時,指定content屬性為內建函式template呼叫/root/redis-master.conf.erb;表示使用這個模板檔案覆蓋/etc/redis.conf檔案內容;

  執行清單,看看對應redis是否監聽在本機192.168.0.52這個地址上呢?

[root@node12 ~]# ss -tnl
State       Recv-Q Send-Q       Local Address:Port                      Peer Address:Port              
LISTEN      0      128                      *:6379                                 *:*                  
LISTEN      0      128                      *:22                                   *:*                  
LISTEN      0      100              127.0.0.1:25                                   *:*                  
LISTEN      0      128                      *:27017                                *:*                  
LISTEN      0      50                       *:3306                                 *:*                  
LISTEN      0      128                     :::80                                  :::*                  
LISTEN      0      128                     :::22                                  :::*                  
LISTEN      0      100                    ::1:25                                  :::*                  
[root@node12 ~]# puppet apply -v --noop redis.pp 
Notice: Compiled catalog for node12.test.org in environment production in 0.33 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1607010053'
Notice: /Stage[main]/Redis::Master/File[/etc/redis.conf]/content: current_value {md5}12e59b058c0ef61ad52bcfa2d4de58ff, should be {md5}52397ae299aa46fe4103654abd62f5fd (noop)
Info: /Stage[main]/Redis::Master/File[/etc/redis.conf]: Scheduling refresh of Service[redis]
Notice: Class[Redis::Master]: Would have triggered 'refresh' from 1 events
Notice: /Stage[main]/Redis/Service[redis]: Would have triggered 'refresh' from 1 events
Notice: Class[Redis]: Would have triggered 'refresh' from 1 events
Notice: Stage[main]: Would have triggered 'refresh' from 2 events
Notice: Finished catalog run in 0.12 seconds
[root@node12 ~]# puppet apply -v  redis.pp       
Notice: Compiled catalog for node12.test.org in environment production in 0.33 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1607010059'
Info: FileBucket got a duplicate file {md5}12e59b058c0ef61ad52bcfa2d4de58ff
Info: /Stage[main]/Redis::Master/File[/etc/redis.conf]: Filebucketed /etc/redis.conf to puppet with sum 12e59b058c0ef61ad52bcfa2d4de58ff
Notice: /Stage[main]/Redis::Master/File[/etc/redis.conf]/content: content changed '{md5}12e59b058c0ef61ad52bcfa2d4de58ff' to '{md5}52397ae299aa46fe4103654abd62f5fd'
Info: /Stage[main]/Redis::Master/File[/etc/redis.conf]: Scheduling refresh of Service[redis]
Notice: /Stage[main]/Redis/Service[redis]: Triggered 'refresh' from 1 events
Notice: Finished catalog run in 0.15 seconds
[root@node12 ~]# ss -tnl
State       Recv-Q Send-Q       Local Address:Port                      Peer Address:Port              
LISTEN      0      128           192.168.0.52:6379                                 *:*                  
LISTEN      0      128                      *:22                                   *:*                  
LISTEN      0      100              127.0.0.1:25                                   *:*                  
LISTEN      0      128                      *:27017                                *:*                  
LISTEN      0      50                       *:3306                                 *:*                  
LISTEN      0      128                     :::80                                  :::*                  
LISTEN      0      128                     :::22                                  :::*                  
LISTEN      0      100                    ::1:25                                  :::*                  
[root@node12 ~]# grep ^bind /etc/redis.conf 
bind 192.168.0.52
[root@node12 ~]# 

  提示:可以看到對應redis已經監聽在192.168.0.52這個地址,並且配置檔案中的bing的值也是192.168.0.52;

  在模板中使用自定義變數

[root@node12 ~]# grep -Ei "^bind|port" redis-master.conf.erb
bind <%= @redis_bindip%>
port <%= @redis_port %>
[root@node12 ~]# 

  在資源中定義變數

[root@node12 ~]# cat redis.pp
class redis{
        package{"redis":
                ensure  => installed,
        }
        service{"redis":
                ensure  => running,
                enable  => true,
                hasrestart      => true,
                restart => 'service redis restart',
        }
}

class redis::master($redis_bindip='0.0.0.0',$redis_port='6379') inherits redis {
        file{"/etc/redis.conf":
                ensure  => file,
                content => template('/root/redis-master.conf.erb'),
        }
        Service["redis"]{
                subscribe       => File["/etc/redis.conf"],
                restart => 'systemctl restart redis'
        }
}

class{"redis::master":
        redis_port      => '16379',
}
[root@node12 ~]# 

  提示;在該資源中宣告類時,傳遞了redis_port這個形參的值為16379,預設的redis_bindip為0.0.0.0;

  執行清單,看看redis是否監聽在本機所有地址的16379埠?

[root@node12 ~]# puppet apply -v  redis.pp 
Warning: Config file /etc/puppet/hiera.yaml not found, using Hiera defaults
Notice: Compiled catalog for node12.test.org in environment production in 0.38 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/share/ruby/vendor_ruby/puppet/type.rb:816:in `set_default')
Info: Applying configuration version '1607010599'
Info: /Stage[main]/Redis::Master/File[/etc/redis.conf]: Filebucketed /etc/redis.conf to puppet with sum 52397ae299aa46fe4103654abd62f5fd
Notice: /Stage[main]/Redis::Master/File[/etc/redis.conf]/content: content changed '{md5}52397ae299aa46fe4103654abd62f5fd' to '{md5}13a04cb20de2d787e0e18c1c13560cab'
Info: /Stage[main]/Redis::Master/File[/etc/redis.conf]: Scheduling refresh of Service[redis]
Notice: /Stage[main]/Redis/Service[redis]: Triggered 'refresh' from 1 events
Notice: Finished catalog run in 0.15 seconds
[root@node12 ~]# ss -tnl
State       Recv-Q Send-Q       Local Address:Port                      Peer Address:Port              
LISTEN      0      128                      *:22                                   *:*                  
LISTEN      0      100              127.0.0.1:25                                   *:*                  
LISTEN      0      128                      *:16379                                *:*                  
LISTEN      0      128                      *:27017                                *:*                  
LISTEN      0      50                       *:3306                                 *:*                  
LISTEN      0      128                     :::80                                  :::*                  
LISTEN      0      128                     :::22                                  :::*                  
LISTEN      0      100                    ::1:25                                  :::*                  
[root@node12 ~]# grep -Ei "^bind|port" /etc/redis.conf 
bind 0.0.0.0
port 16379
[root@node12 ~]# 

  提示:可以看到對應redis監聽在本機所有地址的16379埠,並且對應配置檔案也發生了相應的變數替換;

  以上就是puppet中的變數、正規表示式、流程控制、類和模板的使用和演示;有了這些基本程式設計元素的存在,使得puppet的資源清單變得靈活和通用,我們可以寫一個資源清單適用幾乎所有的不同的系統;

相關文章