自动化运维工具puppet详解(一)

一、puppet 介绍

 

1、puppet是什么

  puppet是一个IT基础设施自动化管理工具,它能够帮助系统管理员管理基础设施的整个生命周期: 供应(provisioning)、配置(configuration)、联动(orchestration)及报告(reporting)。
  基于puppet ,可实现自动化重复任务、快速部署关键性应用以及在本地或云端完成主动管理变更和快速扩展架构规模等。
  遵循GPL 协议(2.7.0-), 基于ruby语言开发。
  2.7.0 以后使用(Apache 2.0 license)
  对于系统管理员是抽象的,只依赖于rubyfacter
  能管理多达40 多种资源,例如:fileusergrouphostpackageservicecronexecyum repo等。

2、puppet的工作机制

1)工作模型

  puppet 通过声明性、基于模型的方法进行IT自动化管理。
  定义:通过puppet 的声明性配置语言定义基础设置配置的目标状态;
  模拟:强制应用改变的配置之前先进行模拟性应用;
  强制:自动、强制部署达成目标状态,纠正任何偏离的配置;
  报告:报告当下状态及目标状态的不同,以及达成目标状态所进行的任何强制性改变;
puppet三层模型
  puppet三层模型如下:

 

2)工作流程

 

3)使用模型

  puppet的使用模型分为单机使用模型master/agent模型,下面我们来看看这两个模型的原理图。
单机使用模型
  实现定义多个manifests --> complier --> catalog --> apply

 

 master/agent模型
  master/agent模型实现的是集中式管理,即 agent 端周期性向 master 端发起请求,请求自己需要的数据。然后在自己的机器上运行,并将结果返回给 master 端。
  架构和工作原理如下:

架构

 

                           master/agent模式架构

工作原理

 

               master/agent模式工作原理

3、puppet 名词解释

  • 资源:是puppet的核心,通过资源申报,定义在资源清单中。相当于ansible中的模块,只是抽象的更加彻底。
  • 类:一组资源清单。
  • 模块:包含多个类。相当于ansible中的角色
  • 站点清单:以主机为核心,应用哪些模块。

二、puppet 资源详解

  接下来,我们就以单机模式来具体介绍一下puppet的各个部分。

 

1、程序安装及环境

  首先,我们还是来安装一下puppetpuppet的安装可以使用源码安装,也可以使用rpm(官方提供)、epel源、官方提供的yum仓库来安装(通过下载官方提供的rpm包可以指定官方的yum仓库)。
  在这里,我们就是用 yum 安装的方式。

[root@localhost ~]# yum install -y puppet

安装完成过后,我们可以通过rpm -ql puppet | less来查看一下包中都有一些什么文件。
  其中主配置文件为/etc/puppet/puppet.conf,使用的主程序为/usr/bin/puppet

[root@localhost ~]# rpm -ql puppet | less
/etc/NetworkManager
/etc/NetworkManager/dispatcher.d
/etc/NetworkManager/dispatcher.d/98-puppet
/etc/logrotate.d/puppet
/etc/puppet
/etc/puppet/auth.conf
/etc/puppet/modules
/etc/puppet/puppet.conf
/usr/bin/extlookup2hiera
/usr/bin/puppet
/usr/bin/start-puppet-agent
/usr/bin/start-puppet-ca
/usr/bin/start-puppet-master
/usr/lib/systemd/system/puppet.service
/usr/lib/systemd/system/puppetagent.service
/usr/share/doc/puppet-3.6.2
/usr/share/doc/puppet-3.6.2/LICENSE
/usr/share/doc/puppet-3.6.2/README.md
/usr/share/doc/puppet-3.6.2/examples
/usr/share/doc/puppet-3.6.2/examples/hiera
/usr/share/doc/puppet-3.6.2/examples/hiera/README.md
/usr/share/doc/puppet-3.6.2/examples/hiera/etc
/usr/share/doc/puppet-3.6.2/examples/hiera/etc/hiera.yaml
/usr/share/doc/puppet-3.6.2/examples/hiera/etc/hieradb
/usr/share/doc/puppet-3.6.2/examples/hiera/etc/hieradb/common.yaml
/usr/share/doc/puppet-3.6.2/examples/hiera/etc/hieradb/dc1.yaml
/usr/share/doc/puppet-3.6.2/examples/hiera/etc/hieradb/development.yaml
/usr/share/doc/puppet-3.6.2/examples/hiera/etc/puppet.conf
/usr/share/doc/puppet-3.6.2/examples/hiera/modules
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/data
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/data/manifests
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/data/manifests/common.pp
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/ntp
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/ntp/manifests
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/ntp/manifests/config.pp
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/ntp/manifests/data.pp
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/ntp/templates
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/ntp/templates/ntp.conf.erb
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/users
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/users/manifests
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/users/manifests/common.pp
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/users/manifests/dc1.pp
/usr/share/doc/puppet-3.6.2/examples/hiera/modules/users/manifests/development.pp
[root@localhost ~]# 

2、puppet 资源简介

 

1)资源抽象

   puppet 从以下三个维度来对资源完成抽象:

  1. 相似的资源被抽象成同一种资源**“类型”** ,如程序包资源、用户资源及服务资源等;
  2. 将资源属性或状态的描述与其实现方式剥离开来,如仅说明安装一个程序包而不用关心其具体是通过yum、pkgadd、ports或是其它方式实现;
  3. 仅描述资源的目标状态,也即期望其实现的结果,而不是其具体过程,如“确定nginx 运行起来” 而不是具体描述为“运行nginx命令将其启动起来”;

  这三个也被称作puppet 的资源抽象层(RAL)
  RAL 由type( 类型) 和provider( 提供者,即不同OS 上的特定实现)组成。
 

2)资源定义

  资源定义通过向资源类型的属性赋值来实现,可称为资源类型实例化;
  定义了资源实例的文件即清单,manifest;
  定义资源的语法如下:

type {'title':
    attribute1     => value1,
    atrribute2    => value2,
    ……
}

  注意:type必须使用小写字符;title是一个字符串,在同一类型中必须惟一;每一个属性之间需要用“,”隔开,最后一个“,”可省略。
  例如,可以同时有名为nginx 的“service”资源和“package”资源,但在“package” 类型的资源中只能有一个名为“nginx”的资源。

3)资源属性中的三个特殊属性:

Namevar:可简称为name;
ensure:资源的目标状态;
Provider:指明资源的管理接口;

3、常用资源总结

1)查看资源
  我们可以使用puppet describe来打印有关Puppet资源类型,提供者和元参数的帮助。使用语法如下:

puppet describe [-h|--help] [-s|--short] [-p|--providers] [-l|--list] [-m|--meta] [type]
    -l:列出所有资源类型;
    -s:显示指定类型的简要帮助信息;
    -m:显示指定类型的元参数,一般与-s一同使用;
 

2)group:管理系统上的用户组。
  查看使用帮助信息:

[root@localhost ~]# puppet describe group -s -m

group
=====
Manage groups. On most platforms this can only create groups.
Group membership must be managed on individual users.
On some platforms such as OS X, group membership is managed as an
attribute of the group, not the user record. Providers must have
the feature 'manages_members' to manage the 'members' property of
a group record.


Parameters
----------
    allowdupe, attribute_membership, attributes, auth_membership, ensure,
    forcelocal, gid, ia_load_module, members, name, system

Meta Parameters
---------------
    alias, audit, before, loglevel, noop, notify, require, schedule, stage,
    subscribe, tag

Providers
---------
    aix, directoryservice, groupadd, ldap, pw, windows_adsi
属性:
    name:组名,可以省略,如果省略,将继承title的值;
    gid:GID;
    system:是否为系统组,true OR false;
    ensure:目标状态,present/absent;
    members:成员用户;

简单举例如下:

[root@localhost puppet]# mkdir ppp
[root@localhost puppet]# cd ppp/
[root@localhost ppp]# vi test.pp

group{'liujunjun':
        gid     => 2000,
        ensure  => present,
}
user{'liujunjun':
        uid     => 2000,
        gid     => 2000,
        shell   => '/bin/bash',
        home    => '/home/liujunjun',
        ensure  => present,
}
[root@localhost ppp]# puppet apply -v --noop test.pp  试动行。
[root@localhost ppp]# puppet apply -v test.pp Notice: Compiled catalog for localhost in environment production in 0.27 seconds Info: Applying configuration version '1579249129' Notice: /Stage[main]/Main/Group[liujunjun]/ensure: created Notice: /Stage[main]/Main/User[liujunjun]/ensure: created Info: Creating state file /var/lib/puppet/state/state.yaml Notice: Finished catalog run in 0.13 seconds
[root@localhost ppp]# tail -1 /etc/group
liujunjun:x:2000:

3)user:管理系统上的用户。
  查看使用帮助信息:

[root@localhost ppp]# puppet describe user -m -s

user
====
Manage users.  This type is mostly built to manage system
users, so it is lacking some features useful for managing normal
users.
This resource type uses the prescribed native tools for creating
groups and generally uses POSIX APIs for retrieving information
about them.  It does not directly modify `/etc/passwd` or anything.
**Autorequires:** If Puppet is managing the user's primary group (as
provided in the `gid` attribute), the user resource will autorequire
that group. If Puppet is managing any role accounts corresponding to the
user's roles, the user resource will autorequire those role accounts.


Parameters
----------
    allowdupe, attribute_membership, attributes, auth_membership, auths,
    comment, ensure, expiry, forcelocal, gid, groups, home, ia_load_module,
    iterations, key_membership, keys, managehome, membership, name,
    password, password_max_age, password_min_age, profile_membership,
    profiles, project, purge_ssh_keys, role_membership, roles, salt, shell,
    system, uid

Meta Parameters
---------------
    alias, audit, before, loglevel, noop, notify, require, schedule, stage,
    subscribe, tag

Providers
---------
    aix, directoryservice, hpuxuseradd, ldap, pw, user_role_add, useradd,
    windows_adsi
属性:
    name:用户名,可以省略,如果省略,将继承title的值;
    uid: UID;
    gid:基本组ID;
    groups:附加组,不能包含基本组;
    comment:注释; 
    expiry:过期时间 ;
    home:用户的家目录; 
    shell:默认shell类型;
    system:是否为系统用户 ;
    ensure:present/absent;
    password:加密后的密码串; 
[root@localhost ppp]# cat test2.pp 
user{'keerr0':
        ensure => present,
        system => false,        #是否为系统用户。
        comment => 'Test User',    #注释
        shell => '/bin/bash',      #默认shell类型
        home => '/home/keerr0',     #用户的家目录。
        managehome => true,
        groups => 'liujunjun',
        uid => 3000,
        }
[root@localhost ppp]# puppet apply -v test2.pp
Notice: Compiled catalog for localhost in environment production in 0.17 seconds
Info: Applying configuration version '1579250211'
Notice: /Stage[main]/Main/User[keerr0]/ensure: created
Notice: Finished catalog run in 0.12 seconds

4)package:puppet的管理软件包。
  查看使用帮助信息:

[root@localhost ppp]# puppet describe package -m -s

package
=======
Manage packages.  There is a basic dichotomy in package
support right now:  Some package types (e.g., yum and apt) can
retrieve their own package files, while others (e.g., rpm and sun)
cannot.  For those package formats that cannot retrieve their own files,
you can use the `source` parameter to point to the correct file.
Puppet will automatically guess the packaging format that you are
using based on the platform you are on, but you can override it
using the `provider` parameter; each provider defines what it
requires in order to function, and you must meet those requirements
to use a given provider.
**Autorequires:** If Puppet is managing the files specified as a
package's `adminfile`, `responsefile`, or `source`, the package
resource will autorequire those files.


Parameters
----------
    adminfile, allow_virtual, allowcdrom, category, configfiles,
    description, ensure, flavor, install_options, instance, name,
    package_settings, platform, responsefile, root, source, status,
    uninstall_options, vendor

Meta Parameters
---------------
    alias, audit, before, loglevel, noop, notify, require, schedule, stage,
    subscribe, tag

Providers
---------
    aix, appdmg, apple, apt, aptitude, aptrpm, blastwave, dpkg, fink,
    freebsd, gem, hpux, macports, msi, nim, openbsd, opkg, pacman, pip, pkg,
    pkgdmg, pkgin, pkgutil, portage, ports, portupgrade, rpm, rug, sun,
    sunfreeware, up2date, urpmi, windows, yum, zypper
属性:
    ensure:installed, present, latest, absent, any version string (implies present)
    name:包名,可以省略,如果省略,将继承title的值;
    source:程序包来源,仅对不会自动下载相关程序包的provider有用,例如rpm或dpkg;
    provider:指明安装方式;

简单举例如下:

[root@localhost ppp]# vi package.pp

package{ 'zip':
                ensure  => installed,
        provider    =>  yum
        }
~
[root@localhost ppp]# puppet apply -v package.pp
Notice: Compiled catalog for localhost in environment production in 0.76 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 '1579250994'
Notice: Finished catalog run in 0.21 seconds

5)service:定义服务的状态
  查看使用帮助信息:

[root@localhost ppp]# puppet describe service -s -m

service
=======
Manage running services.  Service support unfortunately varies
widely by platform --- some platforms have very little if any concept of a
running service, and some have a very codified and powerful concept.
Puppet's service support is usually capable of doing the right thing, but
the more information you can provide, the better behaviour you will get.
Puppet 2.7 and newer expect init scripts to have a working status command.
If this isn't the case for any of your services' init scripts, you will
need to set `hasstatus` to false and possibly specify a custom status
command in the `status` attribute. As a last resort, Puppet will attempt to
search the process table by calling whatever command is listed in the `ps`
fact. The default search pattern is the name of the service, but you can
specify it with the `pattern` attribute.
**Refresh:** `service` resources can respond to refresh events (via
`notify`, `subscribe`, or the `~>` arrow). If a `service` receives an
event from another resource, Puppet will restart the service it manages.
The actual command used to restart the service depends on the platform and
can be configured:
* If you set `hasrestart` to true, Puppet will use the init script's restart
command.
* You can provide an explicit command for restarting with the `restart`
attribute.
* If you do neither, the service's stop and start commands will be used.


Parameters
----------
    binary, control, enable, ensure, flags, hasrestart, hasstatus, manifest,
    name, path, pattern, restart, start, status, stop

Meta Parameters
---------------
    alias, audit, before, loglevel, noop, notify, require, schedule, stage,
    subscribe, tag

Providers
---------
    base, bsd, daemontools, debian, freebsd, gentoo, init, launchd, openbsd,
    openrc, openwrt, redhat, runit, service, smf, src, systemd, upstart,
    windows
属性:
    ensure:服务的目标状态,值有true(running)和false(stopped) 
    enable:是否开机自动启动,值有true和false
    name:服务名称,可以省略,如果省略,将继承title的值
    path:服务脚本路径,默认为/etc/init.d/下
    start:定制启动命令
    stop:定制关闭命令
    restart:定制重启命令
    status:定制状态
[root@localhost ppp]# cat service1.pp 
service{'nginx':
        ensure  => true,
        enable  => false
}
CentOS7下的启动不了。

6)file:管理文件、目录、软链接
  查看使用帮助信息:

[root@localhost ppp]# puppet describe file -s -m

file
====
Manages files, including their content, ownership, and permissions.
The `file` type can manage normal files, directories, and symlinks; the
type should be specified in the `ensure` attribute. Note that symlinks
cannot
be managed on Windows systems.
File contents can be managed directly with the `content` attribute, or
downloaded from a remote source using the `source` attribute; the latter
can also be used to recursively serve directories (when the `recurse`
attribute is set to `true` or `local`). On Windows, note that file
contents are managed in binary mode; Puppet never automatically translates
line endings.
**Autorequires:** If Puppet is managing the user or group that owns a
file, the file resource will autorequire them. If Puppet is managing any
parent directories of a file, the file resource will autorequire them.


Parameters
----------
    backup, checksum, content, ctime, ensure, force, group, ignore, links,
    mode, mtime, owner, path, purge, recurse, recurselimit, replace,
    selinux_ignore_defaults, selrange, selrole, seltype, seluser, show_diff,
    source, source_permissions, sourceselect, target, type, validate_cmd,
    validate_replacement

Meta Parameters
---------------
    alias, audit, before, loglevel, noop, notify, require, schedule, stage,
    subscribe, tag

Providers
---------
    posix, windows
[root@localhost ppp]# 
属性:
    ensure:目标状态,值有absent,present,file,directory和link
        file:类型为普通文件,其内容由content属性生成或复制由source属性指向的文件路径来创建;
        link:类型为符号链接文件,必须由target属性指明其链接的目标文件;
        directory:类型为目录,可通过source指向的路径复制生成,recurse属性指明是否递归复制;
    path:文件路径;
    source:源文件;
    content:文件内容;
    target:符号链接的目标文件; 
    owner:定义文件的属主;
    group:定义文件的属组;
    mode:定义文件的权限;
    atime/ctime/mtime:时间戳;
[root@localhost ppp]# vim file1.pp

file{'aaa':
        path    => '/data/aaa',
        source  => '/etc/aaa',
        owner   => 'keerr0',
        mode    => '611',
        }
[root@localhost ppp]# puppet apply -v file1.pp
Notice: Compiled catalog for localhost in environment production in 0.15 seconds
Info: Applying configuration version '1579252230'
Notice: /Stage[main]/Main/File[aaa]/ensure: defined content as '{md5}d41d8cd98f00b204e9800998ecf8427e'
Notice: Finished catalog run in 0.08 seconds
[root@localhost ppp]# ls /data/aaa 
/data/aaa

7)exec:执行命令,慎用。通常用来执行外部命令
  查看使用帮助信息:

[root@localhost ppp]# puppet describe exec -s -m

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*. There are three
main ways for an exec to be idempotent:
* The command itself is already idempotent. (For example, `apt-get update`.)
* The exec has an `onlyif`, `unless`, or `creates` attribute, which prevents
  Puppet from running the command unless some condition is met.
* The exec has `refreshonly => true`, which only allows Puppet to run the
  command when some other resource is changed. (See the notes on refreshing
  below.)
A caution: There's a widespread tendency to use collections of execs to
manage resources that aren't covered by an existing resource type. This
works fine for simple tasks, but once your exec pile gets complex enough
that you really have to think to understand what's happening, you should
consider developing a custom resource type instead, as it will be much
more predictable and maintainable.
**Refresh:** `exec` resources can respond to refresh events (via
`notify`, `subscribe`, or the `~>` arrow). The refresh behavior of execs
is non-standard, and can be affected by the `refresh` and
`refreshonly` attributes:
* If `refreshonly` is set to true, the exec will _only_ run when it receives
an
  event. This is the most reliable way to use refresh with execs.
* If the exec already would have run and receives an event, it will run its
  command **up to two times.** (If an `onlyif`, `unless`, or `creates`
condition
  is no longer met after the first run, the second run will not occur.)
* If the exec already would have run, has a `refresh` command, and receives
an
  event, it will run its normal command, then run its `refresh` command
  (as long as any `onlyif`, `unless`, or `creates` conditions are still met
  after the normal command finishes).
* If the exec would **not** have run (due to an `onlyif`, `unless`, or
`creates`
  attribute) and receives an event, it still will not run.
* If the exec has `noop => true`, would otherwise have run, and receives
  an event from a non-noop resource, it will run once (or run its `refresh`
  command instead, if it has one).
In short: If there's a possibility of your exec receiving refresh events,
it becomes doubly important to make sure the run conditions are restricted.
**Autorequires:** If Puppet is managing an exec's cwd or the executable
file used in an exec's command, the exec resource will autorequire those
files. If Puppet is managing the user that an exec should run as, the
exec resource will autorequire that user.


Parameters
----------
    command, creates, cwd, environment, group, logoutput, onlyif, path,
    refresh, refreshonly, returns, timeout, tries, try_sleep, umask, unless,
    user

Meta Parameters
---------------
    alias, audit, before, loglevel, noop, notify, require, schedule, stage,
    subscribe, tag

Providers
---------
    posix, shell, windows
属性:
    command(namevar):要运行的命令;
    cwd:指定运行该命令的目录;
    creates:文件路径,仅此路径表示的文件不存在时,command方才执行;
    user/group:运行命令的用户身份;
    path:指定命令执行的搜索路径;
    onlyif:此属性指定一个命令,此命令正常(退出码为0)运行时,当前command才会运行;
    unless:此属性指定一个命令,此命令非正常(退出码为非0)运行时,当前command才会运行;
    refresh:重新执行当前command的替代命令;
    refreshonly:仅接收到订阅的资源的通知时方才运行;
[root@localhost ppp]# vim exec1.pp

exec{'cmd':
        command => 'mkdir /data/testdir',
        path => ['/bin','/sbin','/usr/bin','/usr/sbin'],
        #   path => '/bin:/sbin:/usr/bin:/usr/sbin',
        }
[root@localhost ppp]# puppet apply -v exec1.pp
Notice: Compiled catalog for localhost in environment production in 0.05 seconds
Info: Applying configuration version '1579252384'
Notice: /Stage[main]/Main/Exec[cmd]/returns: executed successfully
Notice: Finished catalog run in 0.05 seconds
[root@localhost ppp]# ls /data/testdir/

8)cron:定义周期性任务
  查看使用帮助信息:

[root@localhost ppp]# puppet describe cron -s -m

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).  While the name of the cron job is
not part of the actual job, the name is stored in a comment beginning with
`# Puppet Name: `. These comments are used to match crontab entries created
by Puppet with cron resources.
If an existing crontab entry happens to match the scheduling and command of
a
cron resource that has never been synched, Puppet will defer to the existing
crontab entry and will not create a new entry tagged with the `# Puppet
Name: `
comment.
Example:
    cron { logrotate:
      command => "/usr/sbin/logrotate",
      user    => root,
      hour    => 2,
      minute  => 0
    }
Note that all periodic attributes can be specified as an array of values:
    cron { logrotate:
      command => "/usr/sbin/logrotate",
      user    => root,
      hour    => [2, 4]
    }
...or using ranges or the step syntax `*/2` (although there's no guarantee
that your `cron` daemon supports these):
    cron { logrotate:
      command => "/usr/sbin/logrotate",
      user    => root,
      hour    => ['2-4'],
      minute  => '*/10'
    }
An important note: _the Cron type will not reset parameters that are
removed from a manifest_. For example, removing a `minute => 10` parameter
will not reset the minute component of the associated cronjob to `*`.
These changes must be expressed by setting the parameter to
`minute => absent` because Puppet only manages parameters that are out of
sync with manifest entries.
**Autorequires:** If Puppet is managing the user account specified by the
`user` property of a cron resource, then the cron resource will autorequire
that user.


Parameters
----------
    command, ensure, environment, hour, minute, month, monthday, name,
    special, target, user, weekday

Meta Parameters
---------------
    alias, audit, before, loglevel, noop, notify, require, schedule, stage,
    subscribe, tag

Providers
---------
    crontab
属性:
    command:要执行的任务(命令或脚本);
    ensure:目标状态,present/absent;
    hour:时;
    minute:分;
    monthday:日;
    month:月;
    weekday:周;
    user:以哪个用户的身份运行命令(默认为root);
    target:添加为哪个用户的任务;
    name:cron job的名称;
[root@localhost ppp]# vim cron1.pp

cron{'timesync':
        command => '/usr/sbin/ntpdata 127.0.0.1',
        ensure  => present,
        minute  => '*/3',
        user    => 'root',
        }
[root@localhost ppp]# puppet apply -v cron1.pp
Notice: Compiled catalog for localhost in environment production in 0.06 seconds
Info: Applying configuration version '1579252608'
Notice: /Stage[main]/Main/Cron[timesync]/ensure: created
Notice: Finished catalog run in 0.14 seconds
[root@localhost ppp]# crontab -l
# HEADER: This file was autogenerated at 2020-01-17 17:16:49 +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: timesync
*/3 * * * * /usr/sbin/ntpdata 127.0.0.1
[root@localhost ppp]# 

9)notify:调试输出
  查看使用帮助信息:

[root@localhost ppp]# puppet describe notify -s -m

notify
======
Sends an arbitrary message to the agent run-time log.


Parameters
----------
    message, name, withpath

Meta Parameters
---------------
    alias, audit, before, loglevel, noop, notify, require, schedule, stage,
    subscribe, tag
属性:
    message:记录的信息
    name:信息名称

该选项一般用于master/agent模式中,来记录一些操作的时间,比如重新安装了一个程序呀,或者重启了应用等等。会直接输出到代理机的运行日志中。

  以上,就是我们常见的8个资源。其余的资源我们可以使用puppet describe -l来列出,上文中也已经说过了~

4、资源的特殊属性

  puppet中也提供了beforerequirenotifysubscribe四个参数来定义资源之间的依赖关系和通知关系。

before:表示需要依赖于某个资源
require:表示应该先执行本资源,在执行别的资源
notify:A notify B:B依赖于A,且A发生改变后会通知B;
subscribe:B subscribe A:B依赖于A,且B监控A资源的变化产生的事件;

  同时,依赖关系还可以使用->~>来表示:

-> 表示后资源需要依赖前资源
~> 表示前资源变动通知后资源调用

 

[root@localhost ppp]# vi file.pp 
file{'test.txt':                                        #定义一个文件
                path   => '/data/test.txt',
                ensure  => file,
                source  => '/etc/fstab',
        }

        file{'test.symlink':                            #依赖文件建立超链接
                path   => '/data/test.symlink',
                ensure  => link,
                target  => '/data/test.txt',
                require => File['test.txt'],
        }

        file{'test.dir':                                        #定义一个目录
                path   => '/data/test.dir',
                ensure  => directory,
                source  => '/etc/yum.repos.d/',
                recurse => true,
        }
[root@localhost ppp]# puppet apply -v file.pp 
Notice: Compiled catalog for localhost in environment production in 0.13 seconds
Info: Applying configuration version '1579265561'
Notice: /Stage[main]/Main/File[test.dir]/ensure: created
Notice: /Stage[main]/Main/File[/data/test.dir/epel-testing.repo]/ensure: defined content as '{md5}a9e798ddf2b4e4a2ebda848480fd250d'
Notice: /Stage[main]/Main/File[/data/test.dir/CentOS-Vault.repo]/ensure: defined content as '{md5}9fdd3d91192aa05427c3a9684eeb1345'
Notice: /Stage[main]/Main/File[/data/test.dir/CentOS-Debuginfo.repo]/ensure: defined content as '{md5}e9e506425094f43b5c8f053090dbf4d4'
Notice: /Stage[main]/Main/File[/data/test.dir/CentOS-CR.repo]/ensure: defined content as '{md5}445ed4f0ee3888384e854fb8527a7cde'
Notice: /Stage[main]/Main/File[/data/test.dir/CentOS-fasttrack.repo]/ensure: defined content as '{md5}52d296f7a45f56c85d18473eca5bab16'
Notice: /Stage[main]/Main/File[/data/test.dir/CentOS-Media.repo]/ensure: defined content as '{md5}1d7797c5082bd565facd68c5aa9352bf'
Notice: /Stage[main]/Main/File[/data/test.dir/CentOS-Sources.repo]/ensure: defined content as '{md5}04d662bb1648477bf50e658a20c10145'
Notice: /Stage[main]/Main/File[/data/test.dir/CentOS-Base.repo]/ensure: defined content as '{md5}9098fc723b1e00c92e8515f06980d83e'
Notice: /Stage[main]/Main/File[/data/test.dir/epel.repo]/ensure: defined content as '{md5}bec6648ba75ea3c9bcb93c048e7a087e'
Notice: Finished catalog run in 0.19 seconds

我们还可以使用在最下面统一写依赖关系的方式来定义:

 

[root@localhost data]# cat redis.pp 
package{'reids':
                ensure  => installed,
        }

        file{'/etc/redis.conf':
                source  => '/root/manifets/files/redis.conf',
                ensure  => file,
                owner   => redis,
                group   => root,
                mode    => '0640',
        }

        service{'redis':
                ensure  => running,
                enable  => true,
                hasrestart => true,
        }

        Package['redis'] -> File['/etc/redis.conf'] -> Service['redis'] #定义依赖关系

tag 标签

  如同 anssible 一样,puppet 也可以定义“标签”——tag,打了标签以后,我们在运行资源的时候就可以只运行某个打过标签的部分,而非全部。这样就更方便于我们的操作。
 一个资源中,可以有一个tag也可以有多个。具体使用语法如下:

type{'title':
    ...
    tag => 'TAG1',
}
            
type{'title':
    ...
    tag => ['TAG1','TAG2',...],
}

调用时的语法如下:

 puppet apply --tags TAG1,TAG2,... FILE.PP

 实例
  首先,我们去修改一下redis.pp文件,添加一个标签进去

 

vim redis.pp
	package{'redis':
		ensure  => installed,
	}

	file{'/etc/redis.conf':
		source  => '/root/manifets/file/redis.conf',
		ensure  => file,
		owner   => redis,
		group   => root,
		mode    => '0640',
		tag    => 'instconf'		#定义标签
	}

	service{'redis':
		ensure  => running,
		enable  => true,
		hasrestart => true,
	}

	Package['redis'] -> File['/etc/redis.conf'] -> Service['redis']

  然后,我们手动先开启redis服务:

	systemctl start redis

  现在,我们去修改一下file目录下的配置文件:

vim file/redis.conf 
	requirepass keerya

  接着,我们就去运行redis.pp,我们的配置文件已经修改过了,现在想要实现的就是重启该服务,实现,需要使用密码keer登录:

	puppet apply -v --tags instconf redis.pp
enter description here
 
redis.pp运行结果

  现在,我们就去登录一下redis看看是否生效:

	redis-cli -a keerya
enter description here
 
redis验证

  验证成功,实验完成。

 

5、puppet 变量

  puppet 变量以“$”开头,赋值操作符为“=”,语法为$variable_name=value
数据类型:

  字符型:引号可有可无;但单引号为强引用双引号为弱引用;支持转义符;
  数值型:默认均识别为字符串,仅在数值上下文才以数值对待;
  数组:[]中以逗号分隔元素列表;
  布尔型值:true, false;不能加引号;
  hash:{}中以逗号分隔k/v数据列表; 键为字符型,值为任意puppet支持的类型;{ ‘mon’ => ‘Monday’, ‘tue’ => ‘Tuesday’, };
  undef:从未被声明的变量的值类型;

正则表达式:

  (?<ENABLED OPTION>:<PATTERN>)
  (?-<DISABLED OPTION>:<PATTERN>)
  OPTIONS:
    i:忽略字符大小写;
    m:把.当换行符;
    x:忽略<PATTERN>中的空白字符;
  (?i-mx:PATTERN)
注意:不能赋值给变量,仅能用在接受=~!~操作符的位置;

 

1)puppet的变量种类

  puppet 种类有三种,为facts内建变量用户自定义变量
facts:
  由facter提供;top scope;
内建变量:
  master端变量
    $servername, $serverip, $serverversion
  agent端变量
    $clientcert, $clientversion, $environment
  parser变量
    $module_name
用户自定义变量

 

2)变量的作用域

  不同的变量也有其不同的作用域。我们称之为Scope
  作用域有三种,top scope,node scope,class scope。
  其生效范围排序为:top scope > node scope > class scope

enter description here
 
变量生效范围

  其优先级排序为:top scope < node scope < class scope

 

6、puppet 流程控制语句

  puppet 支持if 语句case 语句selector 语句

 

1)if 语句

  if语句支持单分支,双分支和多分支。具体语法如下:

单分支:
	if CONDITION {
		statement
		……
	}

双分支:
	if CONDITION {
		statement
		……
	}
	else{
		statement
		……		
	}

多分支:
	if CONDITION {
		statement
		……
	}
	elsif CONDITION{
		statement
		……
	}
	else{
		statement
		……		
	}

  其中,CONDITION的给定方式有如下三种:

  • 变量
  • 比较表达式
  • 有返回值的函数

举例

vim if.pp
	if $operatingsystemmajrelease == '7' {
		$db_pkg='mariadb-server'
	}else{
		$db_pkg='mysql-server'
	}

	package{"$db_pkg":
		ensure => installed,
	}
 

2)case 语句

  类似 if 语句,case 语句会从多个代码块中选择一个分支执行,这跟其它编程语言中的 case 语句功能一致。
  case 语句会接受一个控制表达式和一组 case 代码块,并执行第一个匹配到控制表达式的块。
  使用语法如下:

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

  其中,CONTROL_EXPRESSION的给定方式有如下三种:

  • 变量
  • 表达式
  • 有返回值的函数

  各case的给定方式有如下五种:

  • 直接字串;
  • 变量
  • 有返回值的函数
  • 正则表达式模式;
  • default

举例

vim 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'],
	}
 

3)selector 语句

  Selector 只能用于期望出现直接值(plain value) 的地方,这包括变量赋值、资源属性、函数参数、资源标题、其它 selector。
  selector 不能用于一个已经嵌套于于selector 的case 中,也不能用于一个已经嵌套于case 的case 语句中。
  具体语法如下:

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

  其中,CONTROL_EXPRESSION的给定方式有如下三种:

  • 变量
  • 表达式
  • 有返回值的函数

  各case的给定方式有如下五种:

  • 直接子串;
  • 变量;
  • 有返回值的函数;
  • 正则表达式模式;
  • default

  selectors 使用要点:

  1. 整个selector 语句会被当作一个单独的值,puppet 会将控制变量按列出的次序与每个case 进行比较,并在遇到一个匹配的 case 后,将其值作为整个语句的值进行返回,并忽略后面的其它 case。
  2. 控制变量与各 case 比较的方式与 case 语句相同,但如果没有任何一个 case 与控制变量匹配时,puppet 在编译时将会返回一个错误,因此,实践中,其必须提供default case。
  3. selector 的控制变量只能是变量或有返回值的函数,切记不能使用表达式。
  4. 其各 case 可以是直接值(需要加引号) 、变量、能调用返回值的函数、正则表达式模式或 default。
  5. 但与 case 语句所不同的是,selector 的各 case 不能使用列表。
  6. selector 的各 case 的值可以是一个除了 hash 以外的直接值、变量、能调用返回值的函数或其它的 selector。

举例

vim selector.pp
	$pkgname = $operatingsystem ? {
		/(?i-mx:(ubuntu|debian))/       => 'apache2',
		/(?i-mx:(redhat|fedora|centos))/        => 'httpd',
		default => 'httpd',
	}
	package{"$pkgname":
		ensure  => installed,
	}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

posted @ 2020-01-17 17:21  星火撩原  阅读(903)  评论(0编辑  收藏  举报