111-puppet

一.運維層次分類

OS Provision:

bare metal:pxe, cobbler
virutal machine:image file template
Configuration:
ansible(agentless)
puppet(master/agent)(ruby)
saltstack(python)
Command and Control:
ansible(playbook)
fabric(fab)
func

二. puppet簡介:

單機模型:手動應用清單;
                           程序環境:

配置文件:/etc/puppet/

puppet.conf 

主程序:/usr/bin/puppet 

master/agent:由agent周期性地向Master請求清單并自動應用于本地(默認為30分鐘);
                安裝:        #默認倉庫中已經包含,直接Yum安裝即可
                            puppet命令包:
                                        puppet
                            master:
                                        puppet-server
                                        #server端需要依賴puppet此rpm包
                            agent: 
                                        puppet 
                                        facter (用于收集本地信息)
                                                
                工作架構:
                            111-puppet

 
                        
                        master/agent通信示意圖:
                                master與agent端使用https協議通信,并基于RPC,使用xml格式語言進行數據交換
                                同時,master自身集成了CA證書簽發模塊,可以簽發來自agent端的證書,

                      111-puppet

                          資源部署流程:
                            111-puppet

                                     master需要為每個client使用puppet語言定義資源,并且支持資源在client上的部署測試,
                                     默認情況下,client每30分鐘會自動向master端發送自身狀態信息,master檢測client的狀態
                                     是否與事先定義的期望狀態一致,若不一致,則會強制使其資源狀態與期望的保持一致

                    
                其他簡介:
                     111-puppet


                    puppet 的三層模型
111-puppet

                                                    configuration language :配置語言層
                                                               #提供給用戶,用戶定義資源,編輯資源清單
                                                   transactional layer : 事務層
                                                   resource abstraction layer: 資源層
                                                               #puppet將各種服務抽象成為資源,并自行解決在不同
                                                                   系統版本間的操作
                      資源清單執行流程:
    111-puppet

                                     資源清單manifest首先經過編譯,成為偽代碼catalog, master 將此catalog 發送到
                                    對應的client ,并應用,應用時,首先會檢查資源的狀態信息,看是否與期望的狀態保持
                                    一致,若不一致,則強制執行,使狀態與期望的狀態保持一致

111-puppet

 

         


三. puppet 命令簡介:

    puppet命令使用格式:
Usage: puppet <subcommand> [options] <action> [options]
help              Display Puppet help.
apply             Apply Puppet manifests locally
describe       Display help about resource types
agent            The puppet agent daemon
master          The puppet master daemon
module        Creates, installs and searches for modules on the Puppet Forge
……
‘puppet help <subcommand>’ for help on a specific subcommand.
‘puppet help <subcommand> <action>’ for help on a specific subcommand action.
   puppet apply:
                        #apply 通常用于本地執行一個資源清單
                        #在master節點宕機以后,puppet原有資源清單丟失時,可以使用apply導入備份的原數據
                        # 以恢復工作
Applies a standalone Puppet manifest to the local system.
puppet apply  [-d|–debug] [-v|–verbose] [-e|–execute] [–noop] <file>
                      常用選項:
                                –debug : 顯示調試信息
                                –verbose : 顯示詳細的過程信息
                                –noop :  調試模式,測試但不實際執行 

 四 . puppet 資源

4.1 puppet資源簡介:

資源抽象的緯度(RAL如何抽象資源的?):
類型:具有類似屬性的組件,例如package、service、file;
將資源的屬性或狀態與其實現方式分離;
僅描述資源的目標狀態,也即期望其實現的結果狀態,而不是具體過程; 
RAL由“類型”和提供者(provider);

4.2 puppet describe:

Prints help about Puppet resource types, providers, and metaparameters.
puppet describe [-h|–help] [-s|–short] [-p|–providers] [-l|–list] [-m|–meta] [type]
-l:列出所有資源類型;
-s:顯示指定類型的簡要幫助信息;
-m:顯示指定類型的元參數,一般與-s一同使用;
  1. [root@node74 ~]# puppet describe -l
  2. These are the types known to puppet:
  3. augeas - Apply a change or an array of changes to the ...
  4. computer - Computer object management using DirectorySer ...
  5. cron - Installs and manages cron jobs
  6. exec - Executes external commands
  7. file - Manages files, including their content, owner ...
  8. filebucket - A repository for storing and retrieving file ...
  9. group - Manage groups
  10. host - Installs and manages host entries
  11. interface - This represents a router or switch interface
  12. k5login - Manage the `.k5login` file for a user
  13. macauthorization - Manage the Mac OS X authorization database
  14. mailalias - .. no documentation ..
  15. maillist - Manage email lists
  16. mcx - MCX object management using DirectoryService ...
  17. mount - Manages mounted filesystems, including puttin ...
  18. nagios_command - The Nagios type command
  19. nagios_contact - The Nagios type contact
  20. nagios_contactgroup - The Nagios type contactgroup
  21. nagios_host - The Nagios type host
  22. nagios_hostdependency - The Nagios type hostdependency
  23. nagios_hostescalation - The Nagios type hostescalation
  24. nagios_hostextinfo - The Nagios type hostextinfo
  25. nagios_hostgroup - The Nagios type hostgroup
  26. nagios_service - The Nagios type service
  27. nagios_servicedependency - The Nagios type servicedependency
  28. nagios_serviceescalation - The Nagios type serviceescalation
  29. nagios_serviceextinfo - The Nagios type serviceextinfo
  30. nagios_servicegroup - The Nagios type servicegroup
  31. nagios_timeperiod - The Nagios type timeperiod
  32. notify - .. no documentation ..
  33. package - Manage packages
  34. resources - This is a metatype that can manage other reso ...
  35. router - .. no documentation ..
  36. schedule - Define schedules for Puppet
  37. scheduled_task - Installs and manages Windows Scheduled Tasks
  38. selboolean - Manages SELinux booleans on systems with SELi ...
  39. selmodule - Manages loading and unloading of SELinux poli ...
  40. service - Manage running services
  41. ssh_authorized_key - Manages SSH authorized keys
  42. sshkey - Installs and manages ssh host keys
  43. stage - A resource type for creating new run stages
  44. tidy - Remove unwanted files based on specific crite ...
  45. user - Manage users
  46. vlan - .. no documentation ..
  47. whit - Whits are internal artifacts of Puppet's curr ...
  48. yumrepo - The client-side description of a yum reposito ...
  49. zfs - Manage zfs
  50. zone - Manages Solaris zones
  51. zpool - Manage zpools
                    使用幫助: 
                        #可以查看指定資源類型的定義詳細定義方式
                           puppet describe source_name :

                      eg:    puppet describe group:
                                 111-puppet

 

4.3 資源定義與引用

4.3.1 資源定義

                        #詳細內容可以使用puppet describe source_name查看
資源定義:向資源類型的屬性賦值來實現,可稱為資源類型實例化;
定義了資源實例的文件即清單,manifest;
定義資源的語法:
type{‘title’:
attribute1 =>   value1,
atrribute2         =>   value2,
……
}
注意:type必須使用小寫字符;title是一個字符串,在同一類型中必須惟一;
                        eg:     
                                    service{‘httpd’:
                                            ensure  => running,
                                    }

4.3.2 資源引用

              資源引用方法:
資源引用:
Type[‘title’]
類型的首字母必須大寫;

4.3.3 資源特殊屬性

     資源有特殊屬性:
                1.            名稱變量(namevar):
name可省略,此時將由title表示;
                                                eg:
                                                        package{‘httpd’:
                                                            ensure => installed,
                                                             }                                        
2. ensure:
定義資源的目標狀態;
                                                            
3. 元參數:metaparameters
依賴關系:
before
                                                           #定義資源在指定資源前執行
require
                                                            #定義資源在指定資源之后執行
                                                    eg:
                                                        service{‘nginx’:
                                                            ensure => running,
                                                        }
                                                        package{‘nginx’:
                                                            ensure => install,
                                                            before => Service[‘nginx’],
                                                        }
                                                     或 省略before => Service[‘nginx’],
                                                    直接在service與package之外定義:
                                                    Package[‘nginx’] -> Service[‘nginx’]
通知關系:通知相關的其它資源進行“刷新”操作;
notify
                                                        #一旦此操作執行則通知另一個資源執行刷新
subscribe
                                                        #一旦指定資源執行,本資源則執行刷新
                                                    eg:
                             service{‘httpd’:
ensure  => running,
enable  => true,
restart => ‘systemctl restart httpd.service’,
#       subscribe       => File[‘httpd.conf’],
}
package{‘httpd’:
ensure  => installed,
}
file{‘httpd.conf’:
path    => ‘/etc/httpd/conf/httpd.conf’,
source  => ‘/root/manifests/httpd.conf’,
ensure  => file,
notify  => Service[‘httpd’],
}
           111-puppet

4.4. 資源類型

4.4.1 group                        

                         group:
Manage groups.
#創建組
屬性:
name:組名;
gid:GID;
system:  true|false|yes|no  
                                                           #是否為系統組;
ensure:present/absent;
                                                            #目標狀態(創建或者刪除)
members:成員用戶;

4.4.2 user

user:
Manage users.
#添加與刪除用戶
    屬性:
name:用戶名;
uid: UID;
gid:基于組ID;
groups:附加組,不能包含基本組;
comment:注釋; 
expiry:過期時間 ;
home:家目錄; 
shell:默認shell類型;
system:是否為系統用戶 ;
ensure:present/absent;
password:加密后的密碼串; 

4.4.3 package

package:
Manage packages.
     #安裝或者卸載指定程序
屬性:
ensure:installed | present | latest  | absent
name:包名;
source => /path to rpm_file
                                        #安裝指定路徑下的rpm包
                                        #僅對不會自動下載相關程序包的provider有用,例如rpm或dpkg;
         providers : 指定源,一般可以不用定義,puppet會自動根據系統來選擇
                       
                        eg:
                                package {‘nginx’:
                                       ensure => installd,
                                       name => ‘nginx’,
                                        providers   => ‘yum’,
                                   }

4.4.4 service 

service:
Manage running services.
屬性:
ensure:running | stopped
                                      Whether a service should be running. Valid values are `stopped` (also called `false`),  
                                            `running` (also called `true`).
                                        #定義是否運行服務
enable: true | false
                                       Whether a service should be enabled to start at boot. Valid values are `true`, `false`, 
                                               `manual`.
                                        #定義是否開啟自啟動
name:  #服務名稱
path:The search path for finding init scripts.  Multiple values should be separated by colons
                                         or provided as an array. 
                                        #服務腳本的搜索路徑,默認為/etc/init.d/;
hasrestart:若腳本支持restart ,則此項為true, 不然則為false
hasstatus:若沒有腳本,則此項設置為false
restart:Specify a *restart* command manually.  If left unspecified, the service will be stopped
                                      and then started.
                                        #當服務腳本不支持restart時,定義此項,實現先stop.再start
                                        # 通常用于定義reload操作;
                                    eg:
                                           restart => ‘/usr/sbin/nginx -t && /usr/sbin/nginx -s reload’,
                        start : 定義服務使用指定腳本來啟動
                                      eg :       start => ‘/usr/sbin/nginx’


4.4.5 file

file:
Manages files, including their content, ownership, and permissions.
#定義一個文件類型,并添加或者刪除
                  屬性:
ensure:Whether the file should exist, and if so what kind of file it should be. 
                                       Possible values are `present`, `absent`, `file`, `directory`, and `link`.
file:類型為普通文件,其內容由content屬性生成或復制由source屬性指向的文件路徑來創建;
link:類型為符號鏈接文件,必須由target屬性指明其鏈接的目標文件;
directory:類型為目錄,可通過source指向的路徑復制生成,recurse屬性指明是否遞歸復制;
path:要創建的文件存放路徑;
source:復制生成時使用的源文件;
content:直接使用此定義的內容生成文件;
target:符號鏈接的目標文件; 
owner:屬主
group:屬組
mode:權限;
atime/ctime/mtime:時間戳;
    
示例1:
file{‘test.txt’:
path    => ‘/tmp/test.txt’,
ensure  => file,
source  => ‘/etc/fstab’,
                                    #復制‘/etc/fstab’到指定主機的/tmp/下命名為test.txt
}
file{‘test.symlink’:
path    => ‘/tmp/test.symlink’,
ensure  => link,
target  => ‘/tmp/test.txt’,
require => File[‘test.txt’],
                                    #在 File[‘test.txt’]執行之后,以/tmp/test.txt為源文件生成軟鏈接/tmp/test.symlink
}
file{‘test.dir’:
path    => ‘/tmp/test.dir’,
ensure  => directory,
source  => ‘/etc/yum.repos.d/’,
recurse => true,
}
示例2:
service{‘httpd’:
ensure  => running,
enable  => true,
restart => ‘systemctl restart httpd.service’,
#       subscribe       => File[‘httpd.conf’],
}
package{‘httpd’:
ensure  => installed,
}
file{‘httpd.conf’:
path    => ‘/etc/httpd/conf/httpd.conf’,
source  => ‘/root/manifests/httpd.conf’,
ensure  => file,
notify  => Service[‘httpd’],
}
Package[‘httpd’] -> File[‘httpd.conf’] -> Service[‘httpd’]

4.4.6 exec

   exec:
Executes external commands. Any command in an `exec` resource 
                   #定義在指定條件下時,才執行相關的命令                
                **must** be able to run multiple times without causing harm — that is, it must be *idempotent*
command (*namevar*):要運行的命令;
cwd:The directory from which to run the command.
creates:文件路徑,僅此路徑表示的文件不存在時,command方才執行;
user/group:運行命令的用戶身份;
path:The search path used for command execution. Commands must be fully qualified if no                                                                                        path is specified.
onlyif:此屬性指定一個命令,此命令正常(退出碼為0)運行時,當前command才會運行;
unless:此屬性指定一個命令,此命令非正常(退出碼為非0)運行時,當前command才會運行;
                                        (與onlyif 相反)
refresh:重新執行當前command的替代命令;
refreshonly:僅接收到訂閱的資源的通知時方才運行;
                            eg:
                                exec{‘mkdir’:
                                                command => ‘mkidr /tmp/hello.dir’,
                                                path => ‘/bin:/sbin:/usr/bin’,
                                                creates => ‘/tmp/hello.dir’
                                                #unless => ‘test -d /tmp/hello.dir’
                                        當creates檢測到/tmp/hello.dir不存在時,執行command— ‘mkidr /tmp/hello.dir’,
                                         path 為環境變量PATH,供mkdir使用
                                        unless與creates類似,二者用一個即可

4.4.7 cron    

cron:
Installs and manages cron jobs.  Every cron resource created by Puppet requires a command 
                        and at least one periodic attribute (hour, minute, month, monthday, weekday, or special).
command:要執行的任務;
ensure:present/absent;
hour:指定小時單位
minute:  指定分鐘單位
monthday: 工作日 
month: 月
weekday:周末
user:添加在哪個用戶之上;
name:cron job的名稱;
示例:
cron{‘timesync’:
command => ‘/usr/sbin/ntpdate 10.1.0.1 &> /dev/null’,
ensure  => present,
minute  => ‘*/3’,
user    => ‘root’,
}

4.4.8 notify

notify:
Sends an arbitrary message to the agent run-time log.
#發送一條信息記錄到日志中
屬性:
message:信息內容
name:信息名稱;
                    

 

                   #puppet 還有幾十種資源,詳情自行查閱資源 

4.5 資源清單創建示例

                    在任意目錄下創建manifest目錄,并在manifest中創建以”.pp”結尾的資源清單
                   
                   eg:     
                            mkdir /puppet/manifest
                            vim /puppet/manifest/group.pp:
                                group {‘nginx’:
                                        name => nginx,
                                        ensure => present,
                                        gid  => 1000,
                                        system => no,
                                }
                          本地執行:
                                puppet apply –verbose /puppet/manifest/group.pp
                         111-puppet

 


五. puppet variable (變量 )

$variable_name=value
            示例:
                   111-puppet

 

5.1 數據類型:

字符型:引號可有可無;但單引號為強引用,雙引號為弱引用;
數值型:默認均識別為字符串,僅在數值上下文才以數值對待;
數組:[ ]中以逗號分隔元素列表;
布爾型值:true, false;
hash:{}中以逗號分隔k/v數據列表; 鍵為字符型,值為任意puppet支持的類型;
                                   { ‘mon’ => ‘Monday’, ‘tue’ => ‘Tuesday’, };
undef:從未被聲明的變量的值類型即為undef;也可手動為某變量賦予undef值,
                                        即直接使用不加引號的undef字符串 ;

5.2 正則表達式

正則表達式:
(?<ENABLED OPTION>:<PATTERN>)
(?-<DISABLED OPTION>:<PATTERN>)
OPTIONS:
i:忽略字符大小寫;
                                            #直接使用i 表示忽略,而 -i 則表示不忽略
m:把” . “當換行符;
x:忽略<PATTERN>中的空白字符
常用組合: i-mx 忽略大小寫
注意: 不能賦值給變量 ,僅能用在接受=~或!~操作符的位置;

5.3 puppet的變量類型

5.3.1 facts

facts:一個信息收集工具
                                #puppet-agent將自身主機信息收集并規范后,保存于一系列變量中,
                                   #然后發送給puppet-server端,
由facter提供;top scope;
                       
                        查詢facter:     #用于查詢本機收集到的全部信息(變量)
                                              #這些變量可以用于后續模板中使用
                                facter -p

5.3.2 內建變量

內建變量:
master端變量 
agent端變量 
parser變量
                            111-puppet

 

用戶自定義變量:

5.3.3 變量作用域

變量有作用域,稱為Scope;
全局|頂級作用域 top scope:   $::var_name
節點作用域 node scope
類作用域 class scope
111-puppet

 

111-puppet

 操作符:
111-puppet

 

5.4 puppet 流程控制語句

       流程控制涉及的操作符:
                        111-puppet

 

5.4.1 if 語句

if語句:
if  CONDITION {
} else {
}
CONDITION的給定方式:
(1) 變量
(2) 比較表達式 
(3) 有返回值的函數
示例:
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’],
}
                                        if $operatingsystem =~ /(?i-mx:(centos|redhat|fedora))/ {    
                                                     $pkgname=’httpd’           
                                        }    elsif $operatingsystem =~/(?i-mx:(debian|ubuntu))/ {
                                                       $pkgname=’apache2′
                                        }  else {
                                                       $pagname=’httpd’
                                        }

5.4.2 case 語句

case語句:
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’],
}
111-puppet

 

5.4.3 selector 語句

selector語句:
                                #當變量符合case中的其中一個時,直接返回指定值
CONTROL_VARIABLE ? {
case1 => value1,
case2 => value2,
default => valueN,
}
CONTROL_VARIABLE的給定方法:
(1) 變量
(2) 有返回值的函數
各case的給定方式:
(1) 直接字串;
(2) 變量 
(3) 有返回值的函數
(4) 正則表達式模式;
(5) default 
注意:不能使用列表格式;但可以是其它的selecor;
                                示例1:
$pkgname = $operatingsystem ? {
/(?i-mx:(ubuntu|debian))/       => ‘apache2’,
/(?i-mx:(redhat|fedora|centos))/        => ‘httpd’,
default => ‘httpd’,
}
package{“$pkgname”:
ensure  => installed,
}
示例2:
$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’],
}

六.puppet 類(class)

6.1 puppet的類簡介:

類:puppet中命名的代碼模塊,常用于定義一組通用目標的資源,可在puppet全局調用;
類可以被繼承,也可以包含子類;
      #將多個資源的相關代碼統一起來作為一個類,以供一次性集體調用 
 

6.2 語法格式:

                        普通的類定義:
class NAME {
…puppet code…
}
                        附帶變量賦值的類定義:
class NAME(parameter1, parameter2) {
…puppet code…
}
      eg:
                                    class web(#webserver=’httpd’) {
                                                package{“$webserver”‘:
                                                      ensure => installed,          
                                                 }
                                    }

6.3 類的調用方法

類代碼只有聲明后才會執行,調用方式:
(1) include CLASS_NAME1, CLASS_NAME2, …
(2) 當需要賦予原變量新值的時候,才用此方式調用
                              此時變量的值將以調用時賦予的值為準,而非原定義的值
                                       class{‘CLASS_NAME’:
            attribute => value,
                    }
                       eg:
                                         定義類:
 class web(#webserver=’httpd’) {
                                                package{“$webserver”‘:
                                                      ensure => installed,          
                                                 }
                                          }              
                                        調用類:
                                        class{‘web’:
                                                webserver => ‘nginx’,
                                           }

6.4 示例  

          示例1:
class apache2 {
$webpkg = $operatingsystem ? {
/(?i-mx:(centos|redhat|fedora))/        => ‘httpd’,
/(?i-mx:(ubuntu|debian))/       => ‘apache2’,
default => ‘httpd’,
}
package{“$webpkg”:
ensure  => installed,
}
file{‘/etc/httpd/conf/httpd.conf’:
ensure  => file,
owner   => root,
group   => root,
source  => ‘/tmp/httpd.conf’,
require => Package[“$webpkg”],
notify  => Service[‘httpd’],
}
service{‘httpd’:
ensure  => running,
enable  => true,
}
}
include apache2
示例2:
class web($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’],
}
}
class{‘web’:
webserver       => ‘apache2’,
}


6.5 類的繼承

6.5.1 簡介

       類的繼承: 在原定義的類的基礎上,新增加代碼,即稱為類的繼承
                                    而子類也會具有父類的全部特性(代碼)
                          用作:  減少代碼冗余–當多個模塊的代碼中,有重復的部分,那么重復的部分既可以
                                    定義為一個類;

6.5.2 繼承方式:

               類繼承的方式:
class SUB_CLASS_NAME(子類) inherits PARENT_CLASS_NAME(父|基類) {
…puppet code…
}
或使用完全限定名稱:
                                #即聲明是在某父類下新定義了一個子類,此方式可以直觀看出父類
                          class PARENT_CLASS_NAME::SUB_CLASS_NAME inherits PARENT_CLASS_NAME {
       …puppet code…
                 }

6.5.3 增加或修改父類資源屬性

              子類中 添加|覆蓋 資源屬性的方式:
                            添加:
                                    先調用父類中擁有的資源模塊,并使用”+>“指定添加新的資源屬性, 同時若新屬性相關資源
                            未在父類中出現,還需要額外定義個新的資源;
                                           Service[‘nginx’] {
subscribe +> File[‘ngx-web.conf’],
    }
                            覆蓋(修改)
                                    若希望覆蓋父類中的資源定義的屬性,則直接使用”=>“,而非”+>”
                                          Service[‘nginx’{
subscribe => File[‘ngx-web.conf’],
    }

6.5.4 子類調用        

               子類調用:
                                     include  PARENT_CLASS_NAME::SUB_CLASS_NAME

6.5.5 示例:

                                 eg:
class nginx::web inherits nginx {
Service[‘nginx’] {
subscribe +> File[‘ngx-web.conf’],
                            #在原nginx資源基礎上,增加一個subscribe訂閱屬性,
                                訂閱 File[‘ngx-web.conf’]
}
                                                                #由于原父類中沒有 file {‘ngx-web.conf’},因此在此需要額外定義;
                                                                          file{‘ngx-web.conf’:
path    => ‘/etc/nginx/conf.d/ngx-web.conf’,
ensure  => file,
source  => ‘/root/manifests/ngx-web.conf’,
      }
                                                            }
       示例:
class nginx {
package{‘nginx’:
ensure  => installed,
}
service{‘nginx’:
ensure  => running,
enable  => true,
restart => ‘/usr/sbin/nginx -s reload’,
}
}
class nginx::web inherits nginx {
Service[‘nginx’] {
subscribe +> File[‘ngx-web.conf’],
}
                                                        
file{‘ngx-web.conf’:
path    => ‘/etc/nginx/conf.d/ngx-web.conf’,
ensure  => file,
source  => ‘/root/manifests/ngx-web.conf’,
}
}
class nginx::proxy inherits nginx {
Service[‘nginx’] {
subscribe +> File[‘ngx-proxy.conf’],
}
file{‘ngx-proxy.conf’:
path    => ‘/etc/nginx/conf.d/ngx-proxy.conf’,
ensure  => file,
source  => ‘/root/manifests/ngx-proxy.conf’,
}
}
include nginx::proxy

七.puppet 模板

7.1 簡介

             erb:模板語言,embedded ruby;
          模板文件即為以”.erb”為后綴的文件  
        
puppet兼容的erb語法:
https://docs.puppet.com/puppet/latest/reference/lang_template_erb.html
         
                注意: 模板通常只能幫助以指定內容生成文件

7.2 定義方式:

file{‘title’:
ensure => file,
content => template(‘/PATH/TO/ERB_FILE.erb‘),     #指定模板文件
                                                                                                           #template為內建函數
}                                                                                            
文本文件中內嵌變量替換機制:
   <%= @VARIABLE_NAME %>
                (變量獲取可以使用 fecter -p 產看)
            
                eg:
                       創建一個以模板為內容的文件
                        mkdir -p /puppet/manifest
                        #定義一個資源清單:
                        vim /puppet/manifest/test.pp
                                file{‘/puppet/test.txt’:
                                      content => template(‘/puppet/test.erb’),
                                        #以模板為內容生成/puppet/test.txt文件
                                   }
                        #創建一個模板文件:
                        vim /puppet/test.erb:
                              OS_name: <%= @operatingsystem %>
                              version: <%= @operatingsystemrelease %>
                        #執行
                        puppet apply –verobse –debug /puppet/manifest/test.pp
                         [root@node74 puppet]# cat test.txt 
os_name : CentOS
version : 7.2.1511

7.4 示例:

                        ngx-web.conf中的
class nginx {
package{‘nginx’:
ensure  => installed,
}
service{‘nginx’:
ensure  => running,
enable  => true,
require => Package[‘nginx’],
}
}
class nginx::web inherits nginx {
file{‘ngx-web.conf’:
path    => ‘/etc/nginx/conf.d/ngx-web.conf’,
ensure  => file,
require => Package[‘nginx’],
source  => ‘/root/manifests/nginx/ngx-web.conf’,
}
file{‘nginx.conf’:
path    => ‘/etc/nginx/nginx.conf’,
ensure  => file,
content => template(‘/root/manifests/nginx.conf.erb’),
require => Package[‘nginx’],
}
Service[‘nginx’] {
subscribe => [ File[‘ngx-web.conf’], File[‘nginx.conf’] ],
}
}
include nginx::web

八.puppet 模板

8.1 簡介

puppet模塊:
模塊就是一個按約定的、預定義的結構存放了多個文件或子目錄的目錄,目錄里的這些文件
                 或子目錄必須遵循一定格式的命名規范; 
                #類似ansible 中的 playbook;
        模塊默認存放位置: /etc/puppet/modules    
                    #puppet默認會在此路徑下搜索模塊
                            
        模塊查看:
                        puppet module list      
                    #若已經創建了模塊,可以使用此命令檢測到;
    
        模塊調用:
                    1. 直接在命令行使用puppet -e 調用:
                    puppet apply -e “include module_name”
                        
                    2. 在站點清單中調用
                注意: 勿自調用

8.2 模塊結構

puppet會在配置的路徑下查找所需要的模塊;
MODULES_NAME:
manifests/
init.pp
files/
templates/
lib/
spec/
tests/
注意:模塊名只能以小寫字母開頭,可以包含小寫字母、數字和下劃線;但不能使用”main”和”settings“;
manifests/
init.pp:必須一個類定義,類名稱必須與模塊名稱相同;
files/:靜態文件;
puppet URL:
puppet:///modules/MODULE_NAME/FILE_NAME
templates/:
tempate(‘MOD_NAME/TEMPLATE_FILE_NAME.erb’)
                                    注意: 使用content => template(‘module_name/template_file.erb’)
                                            此處使用相對路徑即可;
                                        eg:
                                              content => template(‘mariadb/my.cnf.erb’),
lib/:插件目錄,常用于存儲自定義的facts以及自定義類型;
spec/:類似于tests目錄,存儲lib/目錄下插件的使用幫助和范例;
tests/:當前模塊的使用幫助或使用范例文件;

8.3 示例:

 mariadb的清單文件示例:
class mariadb($datadir=’/var/lib/mysql’) {
package{‘mariadb-server’:
ensure  => installed,
}
file{“$datadir”:
ensure  => directory,
owner   => mysql,
group   => mysql,
require => [ Package[‘mariadb-server’], Exec[‘createdir’], ],
}
exec{‘createdir’:
command => “mkdir -pv $datadir”,
require => Package[‘mariadb-server’],
path => ‘/bin:/sbin:/usr/bin:/usr/sbin’,
}
file{‘my.cnf’:
path    => ‘/etc/my.cnf’,
content => template(‘mariadb/my.cnf.erb’),
                                            注意: 此處使用相對路徑即可
require => Package[‘mariadb-server’],
notify  => Service[‘mariadb’],
}
service{‘mariadb’:
ensure  => running,
enable  => true,
require => [ Exec[‘createdir’], File[“$datadir”], ],
}
}
 拆分為模塊形式:
                                #創建mariadb模塊的目錄結構
                                mkdir -p /etc/puppet/modules/mariadb/{manifests,files,lib,templates,tests,spec}
                               #復制/etc/my.inf文件到 /etc/puppet/modules/mariadb/templates下
                                        改名為my.inf.erb
                                        修改內容 :       datadir=<%= @mysqldir %>
                                #創建清單列表/etc/puppet/modules/mariadb/manifest/init.pp:
     

  1. class mariadb($mysqldir='/mysql') {
  2. package{'mariadb-server':
  3. ensure => installed,
  4. }
  5. file{'/etc/my.inf':
  6. ensure => file,
  7. content => template('mariadb/my.cnf.erb'),
  8. require => Package['mariadb-server'],
  9. }
  10. file{"$mysqldir":
  11. ensure => directory,
  12. owner => mysql,
  13. group => mysql,
  14. require => Package['mariadb-server'],
  15. }
  16. service{'mariadb':
  17. ensure => running,
  18. enable => true,
  19. subscribe => File['/etc/my.inf'],
  20. }
  21. }
                                    #模塊查看:
[root@node74 manifest]# puppet module list
/etc/puppet/modules
└── mariadb (???)
/usr/share/puppet/modules (no modules installed)
                                    
                                    #模塊調用測試;
                                            puppet apply –verbose –noop –debug -e “include mariadb”

實踐作業:
開發模塊:
memcached
nginx(反代動態請求至httpd,work_process的值隨主機CPU數量而變化)
jdk(輸出JAVA_HOME環境變量)
tomcat
mariadb 
httpd(反代請求至tomcat,ajp連接器;mpm允許用戶通過參數指定)

原創文章,作者:ldt195175108,如若轉載,請注明出處:http://www.www58058.com/62619

(0)
ldt195175108ldt195175108
上一篇 2016-12-04
下一篇 2016-12-04

相關推薦

  • Linux文本搜索工具grep

    Linux文本搜索工具grep Linux文本搜索工具grep grep 基本正則表達式 egrep 擴展正則表達式 fgrep 簡介 grep(全稱Globally search a Regular Expression and Print,全面搜索正則表達式并把行打印出來)是一種強大的文本搜索工具,根據用戶指定的“模式(pattern)”對目標文本進行匹…

    2016-04-05
  • 馬哥教育網絡班22期+第1周課程練習

    一、描述計算機的組成及其功能。 組成:CPU (運算器+控制器),存諸器(內存與硬盤),輸入設備,輸出設備。 運算器:對數據進行加工處理的部件(包括算述運算與邏輯運算)。 控制器:負責從存儲器取出指令,按指令的要求發出控制信號,使各部件協調的,一步步的完成各種操作。 存儲器:計算機記憶或暫存數據的部件 輸入設備:人機接口,負責輸入信息(數據與指令)轉成計算機…

    Linux干貨 2016-08-15
  • M22 Centos設置yum源方法

    實驗目的: 使用虛擬機模擬建立yum源服務器,在客戶機上指定yum源為該服務器。 實驗器材: WMware12安裝Centos6.8虛擬機作為yum服務源 WMware12安裝Centos7.3 作為客戶端訪問yum源服務器 實驗原理圖: 實驗過程: 服務器端: 1、  顯示已經掛載的光盤 #cd /misc/cd #先執行此命令才可以看到光盤掛載…

    2017-03-06
  • Linux命令學習總結:cp命令

    Linux命令學習總結:cp命令 命令簡介:      cp命令用來復制文件或目錄。指令英文原義:copy,copy files and directories      指令所在路徑:/bin/cp 命令語法: cp [OPTION]… [-T]   SO…

    Linux干貨 2017-07-23
  • http加速器varnish

    一、web緩存概述       緩存,又稱加速器,用于加速運行速度較快的設備與較慢設備之間的通信?;诔绦虻倪\行具有局部性特征其能實現加速的功能:       時間局部性:一個數據被訪問之后,在隨后較短的時間內有可能被訪問。   &nbsp…

    2016-11-18
  • Linux用戶和組管理

    使用對象:Linux初學者   Linux系統中用戶和組管理是很重要的一部分內容。許多初學者在學習或剛接觸到用戶管理的時候會覺得很難理解,命令多、選項多、配置文件也多,用命令可以修改,用配置文件也可以修改,三兩下就被繞進去了。其實完全沒必要暈,只要了解了用戶管理的方式,就會很容易理解命令選項與配置文件之間的關系。下面我們就來了解下用戶管理命令與配置…

    Linux干貨 2016-10-23
欧美性久久久久