puppet基礎進階
===============================================================================
概述:
===============================================================================
puppet variable:
1.變量的格式:
★puppet的變量名必須以“$”開頭,f賦值操作符爲“=”:$variable_name=value
★任何正常數據類型(非正則)的值都可以賦予puppet中的變量,如字符串、數值、布爾值、數組、hash以及特殊的undef值(即變量未被賦值)
★puppet的每個變量都有兩個名字:簡短名字和長格式完全限定名字(FQN)完全限定名稱的格式:“$scope::variable”
2.數據類型:
★數據類型:
字符型:引號可有可無;但單引號爲強引用,雙引號爲弱引用;
數值型:默認均識別爲字符串,僅在數值上下文才以數值對待;
數組:[]中以逗號分隔元素列表;
布爾型值:true, false;
hash:{}中以逗號分隔k/v數據列表; 鍵爲字符型,值爲任意puppet支持的類型;如:{ 'mon' => 'Monday', 'tue' => 'Tuesday', };
undef:未賦值型 ;
3.正則表達式:
是一種特殊的數據類型,只能用在特殊的環境當中,不能賦值給變量。
★語法格式:
(?<ENABLED OPTION>:<PATTERN>)
(?-<DISABLED OPTION>:<PATTERN>)
★選項:
i:忽略字符大小寫;-i 表示不忽略字符大小寫;
m:把.當換行符;
x:忽略<PATTERN>中的空白字符
注意:
通常書寫爲 < i-mx >
不能賦值給變量 ,僅能用在接受=~或!~操作符的位置;
4.puppet的變量類型:
★facts:
puppet使用了一個稱作Facter的工具來蒐集系統信息,規範化後將其放進一系列變量中,並傳遞給puppet;
Fact的各變量是Top scope的變量,這意味着可以在個manifest中直接通過${fact name} 訪問所需的fact變量;
facter -p
★內建變量:
master端變量 :$servername,$serrverip,$serverversion
agent端變量 :$environment,$clientcert,$clientversion
parser變量:$module_name
★用戶自定義變量:
==========================================================================
★變量的作用域:scop
☉作用:
scop是一個特定的代碼區域,用於同程序中的其他代碼隔離開來;
在puppet中,scope可用於限定變量及資源默認屬性的作用範圍,但不能用於限定資源名稱及資源引用的生效範圍;
☉scop分類:
任何給定的scope都可以訪問自己的內容,以及接受來自於其父scope、節點scope及top scope的內容;
如圖所示:top scope僅能訪問自己變量和屬性默認值;
節點scope能訪問自己的及top scope的變量和屬性默認值;
example::parent,example::other和example::four能訪問自己的以及節點scope和top scope的變量和默認值;
如果訪問非當前scope中的變量,則需要通過完全限制名稱進行,如:$vhostdir=$apache::params::vhostdir
需要注意的是,top scope的名稱空間爲空,此時,如若要引用其變量,則需要使用類似“$::osfamily”的方式進行。
5.puppet流程控制語句:
★if語句:
☉CONDITION的給定方式:
變量
比較表達式
有返回值的函數
演示:
[root@centos7 manifests]# cat if.pp if $osfamily =~ /(?i-mx:debian)/ { # if條件判斷語句 $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'], # 訂閱File資源,也可以在file中使用notify通知機制 }
★case語句:
☉CONTROL_EXPRESSION:
變量
表達式
有返回值的函數
☉各case的給定方式:
直接字串;
變量
有返回值的函數
正則表達式模式
default
演示:
[root@centos7 manifests]# cat case.pp 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'], }
★selector語句:
☉CONTROL_VARIABLE的給定方法:
變量
有返回值的函數
☉各case的給定方式:
直接字串;
變量
有返回值的函數
正則表達式模式
default
注意:不能使用列表格式;但可以是其它的selecor;
演示:
[root@centos7 manifests]# cat selector.pp $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的類:
1.類的定義,語法格式及調用方式
★定義:
puppet中命名的代碼模塊,常用於定義一組通用目標的資源,可在puppet全局調用;
類可以被繼承,也可以包含子類
★語法格式:
★類代碼只有聲明後纔會執行,調用方式:
示例1:
[root@centos7 manifests]# cat class1.pp class webservice { $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'], } } include webservice
示例2:在外部向類傳遞變量
[root@centos7 manifests]# cat class2.pp 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' # 差UN地參數apache2 }
2.類繼承的方式:
★語法格式:
演示:
# 編輯類繼承方式的文件如下: [root@centos7 manifests]# vim class3.pp class nginx { package{'nginx': ensure => installed, provider => 'rpm', source => '/root/nginx/nginx-1.10.0-1.el7.ngx.x86_64.rpm', } service{'nginx': ensure => running, enable => false, restart => '/usr/sbin/nginx -s reload', 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', } Service['nginx'] { subscribe => File['ngx-web.conf'], } } include nginx::web #======================================================================================= # 提供file資源的源文件 [root@centos7 manifests]# mkdir nginx [root@centos7 manifests]# cp /etc/nginx/conf.d/default.conf ./nginx/ngx-web.conf # 運行類文件 [root@centos7 manifests]# puppet apply --verbose class3.pp Notice: Compiled catalog for centos7 in environment production in 0.89 seconds Info: Applying configuration version '1484478306' Info: Computing checksum on file /etc/nginx/conf.d/ngx-web.conf Info: /Stage[main]/Nginx::Web/File[ngx-web.conf]: Filebucketed /etc/nginx/conf.d/ngx-web.conf to puppet with sum 1d2348ea2b39fef56fcf4431b767fa34 Notice: /Stage[main]/Nginx::Web/File[ngx-web.conf]/content: content changed '{md5}1d2348ea2b39fef56fcf4431b767fa34' to '{md5}4dce452bf8dbb01f278ec0ea9ba6cf40' Info: /Stage[main]/Nginx::Web/File[ngx-web.conf]: Scheduling refresh of Service[nginx] Notice: /Stage[main]/Nginx/Service[nginx]: Triggered 'refresh' from 1 events Notice: Finished catalog run in 0.55 seconds
puppet模板:
1.類的定義,語法格式及調用方式
★erb:
模板語言,embedded ruby;
★puppet兼容的erb語法:
★文本文件中內嵌變量替換機制:
<%= @VARIABLE_NAME %>
示例1:
# 編輯模板文件 [root@centos7 manifests]# vim tem.pp file{'/tmp/template.txt': content => template('/root/manifests/test.erb'), mode => '0640', } # 提供內嵌變量的替換文件 [root@centos7 manifests]# vim test.erb Operating System: <%= @operatingsystem %> Version: <%= @operatingsystemrelease %> # 運行文件tem.pp [root@centos7 manifests]# puppet apply --verbose tem.pp Notice: Compiled catalog for centos7 in environment production in 1.21 seconds Info: Applying configuration version '1484481315' Notice: /Stage[main]/Main/File[/tmp/template.txt]/ensure: defined content as '{md5}9f762979c3dc552a63a74c715a40ae53' Notice: Finished catalog run in 0.03 seconds # 查看執行後的結果可以看到內嵌變量替換爲相應的系統和版本 [root@centos7 manifests]# cat /tmp/template.txt Operating System: CentOS Version: 7.2.1511
示例2:使nginx的配置文件中worker_processes的值爲當前主機的cpu核心數
# 編輯temp2.pp的配置文件如下: [root@centos7 manifests]# vim temp2.pp class nginx { package{'nginx': ensure => installed, provider => 'rpm', source => '/root/nginx/nginx-1.10.0-1.el7.ngx.x86_64.rpm', } service{'nginx': ensure => running, enable => false, 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/nginx.conf.erb'), # 使用模板文件 require => Package['nginx'], } Service['nginx'] { subscribe => [ File['ngx-web.conf'],File['nginx.conf'] ], } } include nginx::web ---------------------------------------------------------------------------------------- # 編輯nginx.conf的模板文件 [root@centos7 manifests]# cat nginx/nginx.conf.erb user nginx; worker_processes <%= @processorcount %>; # 進程數使用內置變量替換 error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; }
# 運行temp2.pp [root@centos7 manifests]# puppet apply --verbose temp2.pp Notice: Compiled catalog for centos7 in environment production in 1.11 seconds Info: Applying configuration version '1484483076' Info: Computing checksum on file /etc/nginx/nginx.conf Info: /Stage[main]/Nginx::Web/File[nginx.conf]: Filebucketed /etc/nginx/nginx.conf to puppet with sum f7984934bd6cab883e1f33d5129834bb Notice: /Stage[main]/Nginx::Web/File[nginx.conf]/content: content changed '{md5}f7984934bd6cab883e1f33d5129834bb' to '{md5}43af14050809e44e3af2515762545a50' Info: /Stage[main]/Nginx::Web/File[nginx.conf]: Scheduling refresh of Service[nginx] Notice: /Stage[main]/Nginx/Service[nginx]: Triggered 'refresh' from 1 events Notice: Finished catalog run in 0.71 seconds #查看nginx的進程數可以看到爲4個 [root@centos7 manifests]# ps aux |grep ^nginx nginx 4614 0.0 0.3 50276 3768 ? S 20:24 0:00 nginx: worker process nginx 4615 0.0 0.3 50276 3768 ? S 20:24 0:00 nginx: worker process nginx 4616 0.0 0.3 50276 3768 ? S 20:24 0:00 nginx: worker process nginx 4617 0.0 0.3 50276 3768 ? S 20:24 0:00 nginx: worker process
puppet模塊:
1.類的定義,語法格式及調用方式
★定義:
模塊就是一個按約定的、預定義的結構存放了多個文件或子目錄的目錄,目錄裏的這些文件或子目錄必須遵循一定格式的命名規範;
puppet會在配置的路徑下查找所需要的模塊;
★模塊名:MODULES_NAME
☉manifests/
init.pp:必須一個類定義,類名稱必須與模塊名稱相同;
☉files/:靜態文件;
puppet URL:puppet:///modules/MODULE_NAME/FILE_NAME
☉templates/:
tempate('MOD_NAME/TEMPLATE_FILE_NAME')
☉lib/:插件目錄,常用於存儲自定義的facts以及自定義類型;
☉spec/:類似於tests目錄,存儲lib/目錄下插件的使用幫助和範例;
☉tests/:當前模塊的使用幫助或使用範例文件;
示例:
1.首先在/etc/puppet/modules下創建固有的目錄,如下:
[root@centos7 ~]# mkdir -pv /etc/puppet/modules/mariadb/{manifests,files,templates,lib,tests,spec} mkdir: created directory ‘/etc/puppet/modules/mariadb’ mkdir: created directory ‘/etc/puppet/modules/mariadb/manifests’ mkdir: created directory ‘/etc/puppet/modules/mariadb/files’ mkdir: created directory ‘/etc/puppet/modules/mariadb/templates’ mkdir: created directory ‘/etc/puppet/modules/mariadb/lib’ mkdir: created directory ‘/etc/puppet/modules/mariadb/tests’ mkdir: created directory ‘/etc/puppet/modules/mariadb/spec’ [root@centos7 ~]# cd /etc/puppet/modules/ [root@centos7 modules]# ls mariadb [root@centos7 modules]# cd mariadb/ [root@centos7 mariadb]# ll total 0 drwxr-xr-x 2 root root 6 Jan 15 23:42 files drwxr-xr-x 2 root root 6 Jan 15 23:42 lib drwxr-xr-x 2 root root 6 Jan 15 23:42 manifests drwxr-xr-x 2 root root 6 Jan 15 23:42 spec drwxr-xr-x 2 root root 6 Jan 15 23:42 templates drwxr-xr-x 2 root root 6 Jan 15 23:42 tests
2.在manifests目錄下定義一個和模塊名稱相同的類文件init.pp
[root@centos7 mariadb]# vim manifests/init.pp class mariadb($mysqldatadir='/var/lib/mysql') { #類mariadb接受參數,默認參數爲/var/lib/mysql package{'mariadb-server': ensure => installed, } file{'/etc/my.cnf': ensure => file, content => template('mariadb/my.cnf.erb'), # 內容爲模板my.cnf.erb中提供的 require => Package['mariadb-server'], } file{"$mysqldatadir": # 冪等性,如果/var/lib/mysql文件不存在就創建 ensure => directory, owner => mysql, group => mysql, require => Package['mariadb-server'], } service{'mariadb': ensure => running, enable => true, subscribe => File['/etc/my.cnf'], # 訂閱file文件 } }
3.在mariadb/templates目錄下創建my.cnf.erb文件
[root@centos7 ~]# cd /etc/puppet/modules/ [root@centos7 modules]# ls mariadb [root@centos7 modules]# cd mariadb/templates/ [root@centos7 files]# cp /etc/my.cnf my.cnf.erb [root@centos7 files]# vim my.cnf.erb [mysqld] datadir=<%= @mysqldatadir %> # 修改爲變量(即:默認變量'/var/lib/mysql')替換 socket=/var/lib/mysql/mysql.sock # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 # Settings user and group are ignored when systemd is used. # If you need to run mysqld under a different user or group, # customize your systemd unit file for mariadb according to the # instructions in http://fedoraproject.org/wiki/Systemd skip_name_resolve = ON innodb_file_per_table = ON #log_bin=master-log #server-id=1 #relay-log=relay-log #relay-log-purge=0 #read-only=1 #ssl #ssl_ca = /var/lib/mysql/ssl/cacert.pem #ssl_cert = /var/lib/mysql/ssl/master.crt #ssl_key = /var/lib/mysql/ssl/master.key #auto_increment_offset=1 #auto_increment_increment=2 #innodb_log_file_size = 50331648 [mysqld_safe] log-error=/var/log/mariadb/mariadb.log pid-file=/var/run/mariadb/mariadb.pid # # include all files from the config directory # !includedir /etc/my.cnf.d
4.查看定義的mariadb模塊,並調用
[root@centos7 mariadb]# puppet module list /etc/puppet/modules └── mariadb (???) /usr/share/puppet/modules (no modules installed) [root@centos7 mariadb]# puppet apply --verbose --noop -e "include mariadb" Warning: Config file /etc/puppet/hiera.yaml not found, using Hiera defaults Notice: Compiled catalog for centos7 in environment production in 1.18 seconds Info: Applying configuration version '1484498009' Notice: /Stage[main]/Mariadb/File[/etc/my.cnf]/content: current_value {md5}a9949c923d1ef818c4c848b1b48b52eb, should be {md5}218c5f66438bf813d07a251ad6939a43 (noop) Info: /Stage[main]/Mariadb/File[/etc/my.cnf]: Scheduling refresh of Service[mariadb] Notice: /Stage[main]/Mariadb/Service[mariadb]: Would have triggered 'refresh' from 1 events Notice: Class[Mariadb]: Would have triggered 'refresh' from 2 events Notice: Stage[main]: Would have triggered 'refresh' from 1 events Notice: Finished catalog run in 0.47 seconds # 也可以像class傳遞參數 [root@centos7 mariadb]# puppet apply --verbose --noop -e "class{'mariadb': mysqldatadir => '/data/mydata'}" Notice: Compiled catalog for centos7 in environment production in 1.12 seconds Info: Applying configuration version '1484498184' Notice: /Stage[main]/Mariadb/File[/etc/my.cnf]/content: current_value {md5}218c5f66438bf813d07a251ad6939a43, should be {md5}a9949c923d1ef818c4c848b1b48b52eb (noop) Info: /Stage[main]/Mariadb/File[/etc/my.cnf]: Scheduling refresh of Service[mariadb] Notice: /Stage[main]/Mariadb/Service[mariadb]: Would have triggered 'refresh' from 1 events Notice: /Stage[main]/Mariadb/File[/data/mydata]/ensure: current_value absent, should be directory (noop) Notice: Class[Mariadb]: Would have triggered 'refresh' from 3 events Notice: Stage[main]: Would have triggered 'refresh' from 1 events Notice: Finished catalog run in 0.39 seconds