天天看點

自動化運維工具之Puppet變量、正規表達式、流程控制、類和模闆

自動化運維工具之Puppet變量、正規表達式、流程控制、類和模闆

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

  前文我們了解了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 ~]# 
      
[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中的模闆

  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的模闆中使用變量替換的使用方式,更多erb模闆語言的使用,請參考官方文檔https://puppet.com/docs/puppet/7.0/lang_template_erb.html#lang_template_erb;

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

作者:Linux-1874

出處:https://www.cnblogs.com/qiuhom-1874/

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利.

繼續閱讀