puppet的相關介紹

一、puppet簡介

        puppet是基於ruby語言開發的一款開源的軟件自動化配置和部署工具,它使用簡單且功能強大,可以C/S模式或獨立運行。


二、puppet工作模式與流程

 ①puppet的工作模式

       定義:使用puppet配置語言定義基礎配置信息;master要指明agent相關配置

          模擬: 模擬測試運行,不真正執行

          強制:強制當前agent與定義的目標狀態保持一致;執行所有配置

          報告:通過puppet api將執行結果發送給接受者; 執行完成agent向master報告

 

 ②Master/Agent的工作流程   

   wKioL1ZPQl-DkjlhAAFXj_kD9do379.png 


三、puppet基本用法

3.1、 puppet的核心組件是資源,下面講解一下幾個常用資源的使用方法:     

# puppet describe --list         //查看puppet的資源列表
# puppet describe 資源名稱      //查看該資源的使用方法
#  puppet apply *.pp                //應用定義的資源清單


①group -- 組管理

常用屬性:
    name               //組名,NameVar
    gid                 //GID
    system {true|false}    //是否爲系統組
    ensure {present |absent}   //創建,刪除
    members             //定義組內成員
例子: test1.pp
group {"redhat":                    //組名
    ensure => present,            //創建
    gid  => 950,                  //組id
    system => true,               //爲系統組,因爲使用的是centos7,1~1000都是系統組id
}
[root@node1 puppet]# puppet apply -v test1.pp       //在本地應用
Notice: Compiled catalog for node1 in environment production in 0.22 seconds
Info: Applying configuration version '1446996520'
Notice: /Stage[main]/Main/Group[redhat]/ensure: created
Notice: Finished catalog run in 0.08 seconds

[root@node1 puppet]# tail -1 /etc/group       //查看結果
redhat:x:950:


② user  -- 用戶管理 

常用屬性:
    comment                //註釋信息
    ensure {present |absent}      //創建,刪除
    expiry                //過期期限
    gid                 //基本組id
    groups               //附加組
    home                //家目錄
    shell               // 默認shell
    name               //用戶名,NameVar
    system {true | false}      //是否爲系統用戶
    uid              //用戶的UID                
    password           //用戶的密碼
例子:test2.pp
user {"centos":
    comment => "this is a centos user",            //註釋
    ensure  => present,                             //創建用戶
    gid     => 950,                                  //組id
    uid     => 950,                                   //用戶id
    home    => "/home/centos",                         //家目錄
    shell   => "/bin/bash",                            //默認shell
    system  => true,                                    //系統用戶
    password => '$1$b1010cc9$V0WJdVPoXCVBI70nse5/H.',      //定義密碼
}


[root@node1 ~]# openssl passwd -1 -salt `openssl rand -hex 4`   //生成密碼的方法
Password: 
$1$b1010cc9$V0WJdVPoXCVBI70nse5/H.
[root@node1 puppet]# puppet apply -v test2.pp 
Notice: Compiled catalog for node1 in environment production in 0.30 seconds
Info: Applying configuration version '1446997336'
Notice: /Stage[main]/Main/User[centos]/ensure: created
Notice: Finished catalog run in 0.09 seconds

[root@node1 puppet]# tail -1 /etc/shadow              //查看密碼文件
centos:$1$b1010cc9$V0WJdVPoXCVBI70nse5/H.:16747:::::: 
[root@node1 puppet]# tail -1 /etc/passwd             //查看用戶文件 
centos:x:950:950:this is a centos user:/home/centos:/bin/bash


③ cron -- 計劃任務

常用屬性:
ensure {present |absent}            //創建,刪除
command                     //要運行的job
hour                       //時,0-23
minute                     //分,0-59
month                      //月,1-12
monthday                    //日,即每月的第幾天,1-31
weekday                     //周,0-7
name                       //定義計劃任務名稱
user                       //運行的用戶
例子:test3.pp
cron {"sync time":
    ensure    => present,                         //創建計劃任務
    command   => '/usr/sbin/ntpdate ntp.sjtu.edu.cn &> /dev/null',  //使用絕對路徑命令
    minute    => '*/5',                       //每5分鐘同步一次時間
}
[root@node1 puppet]# puppet apply -v test3.pp
Notice: Compiled catalog for node1 in environment production in 0.07 seconds
Info: Applying configuration version '1446998027'
Notice: /Stage[main]/Main/Cron[sync time]/ensure: created
Notice: Finished catalog run in 0.26 seconds

[root@node1 puppet]# crontab -l                    //查看結果
# HEADER: This file was autogenerated at 2015-11-08 23:53:48 +0800 by puppet.
# HEADER: While it can still be managed manually, it is definitely not recommended.
# HEADER: Note particularly that the comments starting with 'Puppet Name' should
# HEADER: not be deleted, as doing so could cause duplicate cron jobs.
# Puppet Name: sync time
*/5 * * * * /usr/sbin/ntpdate ntp.sjtu.edu.cn &> /dev/null


④ notify -- 消息

常用屬性:
    message          //要發送的消息的內容;NameVar
例子:test4.pp
notify {"hi":
        message => "hello world",          //輸出消息信息爲 hello world
}
[root@node1 puppet]# puppet apply -v test4.pp
Notice: Compiled catalog for node1 in environment production in 0.05 seconds
Info: Applying configuration version '1448117125'
Notice: hello world                         //應用的結果
Notice: /Stage[main]/Main/Notify[hi]/message: defined 'message' as 'hello world'
Notice: Finished catalog run in 0.04 seconds


⑤ file --文件管理

指明文件內容來源:
    content      //直接給出文件內容,支持\n, \t ===要用雙引號;
    source       //從指定位置下載文件
    ensure {file|directory|link|present|absent}  //文件,目錄,鏈接,創建,刪除
常用屬性:
    force              //強制運行,可用值yes, no, true, false
    group             //文件的屬組
    owner            //文件的屬主
    mode            //指定權限,支持八進制格式權限,以及u,g,o的賦權方式
    path           //目標路徑; 必須爲絕對路徑
    source        //源文件路徑;可以是本地文件路徑(單機模型),也可以使用puppet:///modules/module_name/file_name;
    target   //當ensure爲“link”時,target表示path指向的文件是一個符號鏈接文件,其目標爲此target屬性所指向的路徑;此時content及source屬性自動失效;
例子:test5.pp
file {"/tmp/hello":
   ensure => directory,              //在/tmp目錄下,創建hello目錄
   owner => "centos",                //屬主centos
   group => "redhat",               //屬組redhat
   mode => "400",            //權限爲400,但爲目錄,必然會有x權限,故創建後權限爲500
}

file {"/tmp/test1":           //創建文件test1
   ensure => file,
   owner => "centos",         //屬主爲centos
}

file {"/tmp/link":
   ensure => link,                //創建test1的鏈接文件爲link 
   target => "/tmp/test1",
}
[root@node1 puppet]# puppet apply -v test5.pp 
Notice: Compiled catalog for node1 in environment production in 0.15 seconds
Info: Applying configuration version '1448117739'
Notice: /Stage[main]/Main/File[/tmp/test1]/ensure: created
Notice: /Stage[main]/Main/File[/tmp/hello]/ensure: created
Notice: /Stage[main]/Main/File[/tmp/link]/ensure: created
Notice: Finished catalog run in 0.05 seconds

[root@node1 puppet]# ll /tmp/             //查看結果
total 4
dr-x------ 2 centos redhat 4096 Nov 21 22:55 hello
lrwxrwxrwx 1 root   root     10 Nov 21 22:55 link -> /tmp/test1
-rw-r--r-- 1 centos root      0 Nov 21 22:55 test1


⑥ exec -- 命令管理

常用選項:
    command            //運行的命令;NameVar;
    creates            //此屬性指定的文件不存在時才執行此命令;	
    cwd                //在此屬性指定的路徑下運行命令;
    user               //以指定的用戶身份運行命令;
    group              //指定組;
    onlyif             //給定一個測試命令;僅在此命令執行成功(返回狀態碼爲0)時才運行command指定的命令;
    unless             //給定一個測試命令;僅在此命令執行失敗(返回狀態碼不爲0)時才運行command指定的命令;
    refresh      //接受到其它資源發來的refresh通知時,默認是重新執行exec定義的command,
             //refresh屬性可改變這種行爲,即可指定僅在refresh時運行的命令;
    refreshonly      //僅在收到refresh通知,才運行此資源;
    returns        //期望的狀態返回值,返回非此值時表示命令執行失敗;
    tries          //嘗試執行的次數;
    timeout        //超時時長;
    path           //指明命令搜索路徑,其功能類型PATH環境變量;其值通常爲列表['path1', 'path2', ...];如果不定義此屬性,則必須給定命令的絕對路徑;
例子:test6.pp

exec {"/bin/echo hello > /tmp/hello.txt":
     user => root,
     group => root,
     unless => "/usr/bin/test -e /tmp/hello.txt",     //文件不存在的時候執行echo命令
}
[root@node1 puppet]# puppet apply -v test6.pp 
Notice: Compiled catalog for node1 in environment production in 0.04 seconds
Info: Applying configuration version '1448121368'
Notice: /Stage[main]/Main/Exec[/bin/echo hello > /tmp/hello.txt]/returns: executed successfully
Notice: Finished catalog run in 0.11 seconds

[root@node1 puppet]# cat /tmp/hello.txt       //查看應用結果
hello

注: creates後面直接跟文件,不存在的時候運行命令;

        onlyif或unless後面必須跟判斷語句;

        onlyif執行成功運行命令,unless執行不成功運行命令;


⑦ package -- 軟件包管理

常用選項:
     name             //軟件包名
     ensure {present,installed| latest| absent}   //安裝,安裝最新的,卸載
例子: test7.pp
package {"httpd":
   ensure  => present,
   allow_virtual => false,
}
[root@node1 puppet]# rpm -q httpd
package httpd is not installed

wKiom1ZQianyzeWHAABHimyKy-0842.png


⑧ service -- 服務管理

常用選項:
     ensure {running 運行狀態 | stopped 停止狀態}   //指定服務的目標狀態     
     enable {true | false }    //指定服務是否開機自啓動,並非對所有均有效
     name                     //服務名,默認與title相同
例子:  test8.pp
service {"httpd":
    ensure => running,
    enable => true,
}
[root@node1 puppet]# puppet apply -v test8.pp 
Notice: Compiled catalog for node1 in environment production in 0.48 seconds
Info: Applying configuration version '1448119012'
Notice: /Stage[main]/Main/Service[httpd]/ensure: ensure changed 'stopped' to 'running'
Info: /Stage[main]/Main/Service[httpd]: Unscheduling refresh on Service[httpd]
Notice: Finished catalog run in 0.84 seconds

[root@node1 puppet]# ss -tanl           //查看應用結果 
State       Recv-Q Send-Q             Local Address:Port          Peer Address:Port   
LISTEN      0      128                    :::80                        :::*   

[root@node1 puppet]# systemctl list-unit-files --type service | grep httpd
httpd.service                               enabled


3.2、puppet的資源引用

①資源引用格式: Type['title'] 資源類型首字母要大寫,例Group|Package|File等


②關係的定義

定義依賴關係 :即資源定義有先後順序

    被依賴的資源中使用:before 

            例:創建用戶之前,所定義gid所對應的組應該事先存在,在group中使用

    依賴其它資源的資源:require

            例:依賴對應gid的組,在user中使用 

     ->:鏈式依賴

定義通知關係:

    被依賴的資源中使用:notify(通知)

          例:配置文件使用,當發生改變的時候,通知相應服務進行reload或restart

    監聽其它資源的資源:subscribe (訂閱)

          例:服務中使用,可訂閱對應服務的配置文件

    ~>:鏈式通知


3.3、puppet的數據類型

<1> 字符型:

   ①非結構化文本字符串,可使用引號也可不用;

   ②單引號強引用,雙引號弱引用;

   ③支持轉義符


<2> 數值型:

   整數和浮點數,只有在執行數值計算或比較的時候纔會當做數值型,默認爲字符型


<3> 數組:

  ①[]中括號以逗號分隔的元素

  ②數組中的元素可以是任意數據類型

  ③ 數組的索引從0開始,也可以是負數索引 


<4> 布爾型: 

   true或false,不能加引號


<5> undef:

   未被聲明的變量值的類型


<6> hash:類似集合

  ①鍵值數據類型,key=>value,定義在{}大括號中,以逗號分隔

  ②key必須爲字符型,value可以是任意數據類型

  ③訪問hash類型的數據元素要使用key當索引 


<7> 正則表達式:

 非標準數據類型,不能賦值給變量,只接受=~和!~匹配操作符的位置

 使用方法:/正則表達式/,正則表達式格式

(?<ENABLED  OPTION>:<SUBPATTERN>) ;(?<DISABLED  OPTION>:<SUBPATTERN>)

  例:  =~  /^(?i-mx(centos|fedora))/

    常用的選項: 

        i:忽略字符大小寫

        m:把點當換行符

        x:忽略空白字符和註釋 


3.4、puppet的變量

    puppet的變量名稱必須以“$”開頭,賦值操作符爲“=”

    facter變量:可直接引用

                 查看puppet支持的各facts   

                                # facter -p   

      內置變量 

                客戶端內置: $clientcert ; $clientversion 

                服務器端內置 : $servername ; $serverip; $serverversion ; $module_name


3.5、puppet的類

  用於公共目的的一組資源,是命名的代碼塊,創建後可在puppet全局進行調用,類可以繼承。

3.5.1、類的定義

        ①不帶參數的類   class class_name {

                                            ...puppet code...

                                    }

        ②帶參數的類  calss class_name (param1='value1',param2='value2') {

                                        ...puppet code...

                                  } 

  注意:類名只能包含小寫字母、數字和下載線,且必須以小寫字母開頭 ;類需要聲明後纔可以執行 


3.5.2、類的聲明,常用方式:

 ① 類聲明的方式 1 :

                include class_name1,class_name2, .... 

 ②類聲明的方式2 : 

                class { 'class_name': 

                                ...puppet code...

                           }

       

3.5.3、類的繼承:繼承一個已有的類,並實現覆蓋資源屬性,或向資源屬性追加額外值 (=> , +> )

       定義方式: base_class爲基類,也稱爲父類

                    class base_class {

                            ... puppet code .....

                    } 

                    class base_class::class_name inherits base_class {

                            ... puppet code .....

                    }


3.6、puppet的條件語句語法格式

①if語句

單分支:

         if CONDITION {

                statement

                 ...

          }

雙分支:

       if CONDITION {

             statement

             ...

       }

     else {

            statement

           ...

      }         

多分支:  

         if CONDITION {

                statement

                 ...

         }

          elif CONDITION {

                statement

                 ...

         }

         else {

               statement

               ...

         }    

CONDITION 的用法:

       1、比較表達式

       2、變量引用

       3、有返回值的函數調用


②case語句

    case語句會從多個代碼塊中選擇第一個與控制表達式匹配的塊進行執行

      case CONTROL_EXPRESS {

                    case1,...: { statement }

                     case2,...: { statement }

                      ......

                    default:{ statement }

           }


③selector語句

   selector只能用於期望出現的位置,不能用於一個已經嵌套了selector的case中,也不能用於一個已經嵌套了case的case語句中;如果給出的case都不匹配控制變量,那麼必須定義default case,否則會報錯。

          CONTROL_VARIABLE ? {

                 case1 => value1 ,

                 case2 => value2 ,

                 ......

                 default => valueN

             }   


3.7、puppet的模板

puppet模板: 基於ERB模板語言,在靜態文件中使用變量等編程元素生成適用於多種不同的環境的文本文件(配置文件);

Embedded RuBy,用於實現在文本文件中嵌入ruby代碼,原來的文本信息不會被改變,但ruby代碼會被執行,執行結果將直接替換原來代碼

常用代碼:  <%= Ruby Expression %>  ==== 替換爲表達式的值

                    //一般結合facter獲取系統的信息,修改服務的配置文件使用

  

3.8、puppet模塊

    puppet的模塊定義方法,類似於ansible的roles;定義模塊有助於以結構化、層次化的方式使用puppet。

①模塊定義的目錄層次如下:默認存放在/etc/puppet/modules中,也可在配置文件中修改路徑。

 module_name/   :模塊名稱      
   manifests/  :資源清單                      
     init.pp : 至少應該包含一個與當前模塊名稱同名的類              
   files/     :靜態文件; puppet:///modules/module_name/file_name 
   templates/  :模板文件目錄; template('module_name/template_file_name')    
   lib/        : 插件目錄              
   tests/      :當前模塊的使用幫助文件及示例文件             
   spec/       : 類似於tests目錄,存儲lib目錄下定義的插件的使用幫助及示例文件


②模塊管理命令

USAGE: puppet module <action> [--environment production ][--modulepath $basemodulepath ]
                //模塊的使用方法 動作 使用環境:生產環境  模塊的路徑 
ACTIONS:
  build        Build a module release package.      //創建
  changes      Show modified files of an installed module.  //改變的文件
  generate     Generate boilerplate for a new module.     //生成一個新的模塊
  install      Install a module from the Puppet Forge or a release archive. //安裝模塊
  list         List installed modules           //模塊列表
  search       Search the Puppet Forge for a module.   //搜索模塊
  uninstall    Uninstall a puppet module.            //卸載模塊
  upgrade      Upgrade a puppet module.          //升級模塊


四、安裝配置puppet的Master/Agent 

4.1、配置文件 /etc/puppet/puppet.conf

 顯示或設置配置參數:
     # puppet config print          //顯示所有參數 
     # puppet config set            //設置參數的值

 

4.2、 獲取puppet文檔: 

  # puppet doc --list       // 列出所有的reference參考手冊  
  # puppet doc -r reference_name   // 查看某個reference參考手冊


4.3、配置puppet  --- Master/Agent 

準備工作: 
node1:172.16.116.231     //master,安裝puppet-server,facter
node2:172.16.116.232     //agent,安裝puppet,facter
 
# vim /etc/hosts 
172.16.116.231 node1
172.16.116.232 node2
#關鍵步驟:要讓master和各agent基於ssh主機互信         
#ssh-keygen -t rsa -P '' 
#ssh-copy-id 

############特別強調,不能少~~否則出現下列問題##############
Error: Could not request certificate: Connection refused - connect(2)


1、配置Master:

啓動:首次啓動先查看是否存在問題,如果沒有再使用-D選項(守護進程);
       自動生成的ca證書 /var/lib/puppet/ssl 目錄中
  
[root@node1 ~]# puppet master -v --no-daemonize      //查看相關信息 
Info: Creating a new SSL key for ca
Info: Creating a new SSL certificate request for ca
Info: Certificate Request fingerprint (SHA256): 5D:2F:58:58:37:C3:E5:A5:35:82:D0:3B:8F:36:7A:10:B7:93:C9:3E:CB:E2:EC:13:34:23:50:7A:C6:58:9C:87
Notice: Signed certificate request for ca
Info: Creating a new certificate revocation list
Info: Creating a new SSL key for node1
Info: csr_attributes file loading from /etc/puppet/csr_attributes.yaml
Info: Creating a new SSL certificate request for node1
Info: Certificate Request fingerprint (SHA256): 6A:C8:00:C7:EB:CE:7A:1C:07:6B:8A:44:1C:35:B3:2B:28:7A:DE:5B:64:BE:53:BD:72:AF:8D:4F:D8:2F:9E:E6
Notice: node1 has a waiting certificate request
Notice: Signed certificate request for node1
Notice: Removing file Puppet::SSL::CertificateRequest node1 at '/var/lib/puppet/ssl/ca/requests/node1.pem'
Notice: Removing file Puppet::SSL::CertificateRequest node1 at '/var/lib/puppet/ssl/certificate_requests/node1.pem'
Notice: Starting Puppet master version 3.6.2


2、配置Agent:

[root@node2 ~]# puppet agent --server=node1 -v --no-daemonize --test --noop
Info: Creating a new SSL key for node2
Info: Caching certificate for ca
Info: csr_attributes file loading from /etc/puppet/csr_attributes.yaml
Info: Creating a new SSL certificate request for node2
Info: Certificate Request fingerprint (SHA256): 4B:92:71:6A:48:48:37:36:C1:12:84:63:C1:C1:57:40:7E:58:5C:29:ED:D9:57:F4:B0:79:8D:AE:25:C4:AF:E1
Info: Caching certificate for ca                    //等待ca頒發證書
Exiting; no certificate found and waitforcert is disabled    

 //在node1上顯示如下的信息,說明已收到node2的證書申請
Notice: node2 has a waiting certificate request

         

3、 crt 證書相關操作: 

 puppet cert sign AGENT_HOSTNAME      //給某個agent簽證
      list                           //列出所有的待簽署證書
      sign                           //簽署 
      --all                          //簽署所有,存在隱患,慎用~~~ 
      clean                         //清理指定agent證書
[root@node1 ~]# puppet cert list       //查看所有待簽證書
 "node2" (SHA256) 4B:92:71:6A:48:48:37:36:C1:12:84:63:C1:C1:57:40:7E:58:5C:29:ED:D9:57:F4:B0:79:8D:AE:25:C4:AF:E1
 
[root@node1 ~]# puppet cert sign node2   //給node2簽證
 Notice: Signed certificate request for node2
Notice: Removing file Puppet::SSL::CertificateRequest node2 at '/var/lib/puppet/ssl/ca/requests/node2.pem'


4、測試

[root@node2 ~]# puppet agent --server=node1 -v --no-daemonize  //在agent上查看 
Info: Caching certificate for node2
Info: Caching certificate_revocation_list for ca
Info: Caching certificate for node2
Notice: Starting Puppet client version 3.6.2
Info: Retrieving pluginfacts
Info: Retrieving plugin
Info: Caching catalog for node2
Info: Applying configuration version '1448189086'
Info: Creating state file /var/lib/puppet/state/state.yaml
Notice: Finished catalog run in 0.02 seconds


[root@node1 ~]# puppet master -v --no-daemonize     //在master上查看的結果
Notice: Starting Puppet master version 3.6.2
Info: access[^/catalog/([^/]+)$]: allowing 'method' find
Info: access[^/catalog/([^/]+)$]: allowing $1 access
Info: access[^/node/([^/]+)$]: allowing 'method' find
Info: access[^/node/([^/]+)$]: allowing $1 access
Info: access[/certificate_revocation_list/ca]: allowing 'method' find
Info: access[/certificate_revocation_list/ca]: allowing * access
Info: access[^/report/([^/]+)$]: allowing 'method' save
Info: access[^/report/([^/]+)$]: allowing $1 access
Info: access[/file]: allowing * access
Info: access[/certificate/ca]: adding authentication any
Info: access[/certificate/ca]: allowing 'method' find
Info: access[/certificate/ca]: allowing * access
Info: access[/certificate/]: adding authentication any
Info: access[/certificate/]: allowing 'method' find
Info: access[/certificate/]: allowing * access
Info: access[/certificate_request]: adding authentication any
Info: access[/certificate_request]: allowing 'method' find
Info: access[/certificate_request]: allowing 'method' save
Info: access[/certificate_request]: allowing * access
Info: access[/v2.0/environments]: allowing 'method' find
Info: access[/v2.0/environments]: allowing * access
Info: access[/]: adding authentication any
Info: Inserting default '/status' (auth true) ACL
Info: Caching node for node2
Info: Caching node for node2
Notice: Compiled catalog for node2 in environment production in 0.02 seconds


5、定義該agnet的站點清單;在master端:

        (1)安裝所有要用到的模塊:

    # puppet module install module_name

      

     (2) 定義 site mainfest ;各agent的站點清單

  # vim /etc/puppet/mainfests/site.pp 
     node 'NODE_NAME' {
     ... puppet code ...  (類聲明,也可以定義資源或變量等)
     }
      
  例如 :     
     node "node2" {
        include httpd::web ,   
      }

至此~puppet的相關介紹及Master/Agent搭建完成~~O(∩_∩)O~~




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章