puppet基础篇(练习篇)
本文分为两部分:一、安装配置及命令用法;二、puppet资源基础练习
1.安装配置及命令用法
#在epel仓库安装 yum install ./facter-2.4.6-1.el7.x86_64.rpm ./puppet-3.8.7-1.el7.noarch.rpm [root@node1 puppet]# puppet helpUsage: puppet <subcommand> [options] <action> [options] puppet apply apply Apply Puppet manifests locally puppet apply --help SYNOPSIS ----------- Applies a standalone Puppet manifest to the local system. puppet apply [-h|--help] [-V|--version] [-d|--debug] [-v|--verbose] [-e|--execute] [--detailed-exitcodes] [-L|--loadclasses] [-l|--logdest syslog|eventlog|<FILE>|console] [--noop] [--catalog <catalog>] [--write-catalog-summary] <file>* --noop:Use 'noop' mode where Puppet runs in a no-op or dry-run mode. puppet describedescribe Display help about resource types puppet describe [-h|--help] [-s|--short] [-p|--providers] [-l|--list] [-m|--meta] OPTIONS-------* --help: Print this help text* --providers: Describe providers in detail for each type #列出所有的资源类型 * --list: List all types #列出指定类型的参数,一般与-s一同使用 * --meta: List all metaparameters #列出指定类型的简要帮助信息 * --short: List only parameters without detail #列出puppet的资源类型 [root@node1 puppet]# puppet describe -lThese are the types known to puppet: augeas - Apply a change or an array of changes to the ... computer - Computer object management using DirectorySer ... cron - Installs and manages cron jobs exec - Executes external commandsfile - Manages files, including their content, owner ... filebucket - A repository for storing and retrieving file ...group - Manage groupshost - Installs and manages host entriesinterface - This represents a router or switch interfacek5login - Manage the `.k5login` file for a usermacauthorization - Manage the Mac OS X authorization databasemailalias - .. no documentation .. maillist - Manage email lists mcx - MCX object management using DirectoryService ...mount - Manages mounted filesystems, including puttin ... nagios_command - The Nagios type command nagios_contact - The Nagios type contact nagios_contactgroup - The Nagios type contactgroup nagios_host - The Nagios type host nagios_hostdependency - The Nagios type hostdependency nagios_hostescalation - The Nagios type hostescalation nagios_hostextinfo - The Nagios type hostextinfo nagios_hostgroup - The Nagios type hostgroup nagios_service - The Nagios type service nagios_servicedependency - The Nagios type servicedependency nagios_serviceescalation - The Nagios type serviceescalation nagios_serviceextinfo - The Nagios type serviceextinfo nagios_servicegroup - The Nagios type servicegroup nagios_timeperiod - The Nagios type timeperiod notify - .. no documentation ..package - Manage packages resources - This is a metatype that can manage other reso ... router - .. no documentation .. schedule - Define schedules for Puppet scheduled_task - Installs and manages Windows Scheduled Tasks selboolean - Manages SELinux booleans on systems with SELi ... selmodule - Manages loading and unloading of SELinux poli ... service - Manage running services ssh_authorized_key - Manages SSH authorized keyssshkey - Installs and manages ssh host keysstage - A resource type for creating new run stages tidy - Remove unwanted files based on specific crite ...user - Manage usersvlan - .. no documentation .. whit - Whits are internal artifacts of Puppet's curr ... yumrepo - The client-side description of a yum reposito ... zfs - Manage zfs zone - Manages Solaris zones zpool - Manage zpools #查看组类型的用法 puppet describe group #各种属性的介绍 - **ensure** Create or remove the group. Valid values are `present`, `absent`. - **gid** The group ID. - **members** The members of the group. - **name** The group name. - **system** Whether the group is a system group with lower GID.
2.puppet资源基础练习
核心类型: group: 组 user:用户 packge:程序包 service:服务 file:文件 exec:执行自定义命令,要求幂等 cron:周期性任务计划 notify:通知###资源定义 通过资源类型的属性赋值来实现资源定义,这也称为资源类型实例化。定义资源实例化的文件即清单:manifest ###属性:attribute 资源属性中三个个特殊属性(几乎所有的资源中都有) namevar,可简写为name,描述资源的名字 ensure,描述资源的目标状态 provider,资源的管理接口 语法; type {'title': attribute1 => value1, atrribute2 => value2, …… } #创建清单的目录 [root@node1 puppet]# mkdir manifests [root@node1 puppet]# cd manifests/ ###资源类型 1.group group{'nginx': ensure => present, name => 'nginx', system => true, } #干跑模式 [root@node1 manifests]# puppet apply --verbose --noop first.pp Notice: Compiled catalog for node1.localdomain in environment production in 0.15 seconds Info: Applying configuration version '1500559833' Notice: /Stage[main]/Main/Group[nginx]/ensure: current_value absent, should be present (noop) Notice: Class[Main]: Would have triggered 'refresh' from 1 events Notice: Stage[main]: Would have triggered 'refresh' from 1 events Notice: Finished catalog run in 0.04 seconds #执行 [root@node1 manifests]# puppet apply --verbose --debug first.pp Info: Applying configuration version '1500560157' Debug: Executing '/usr/sbin/groupadd -r nginx' Notice: /Stage[main]/Main/Group[nginx]/ensure: created Notice: Finished catalog run in 0.08 seconds #查看 [root@node1 manifests]# tail -1 /etc/group nginx:x:995:2.user 2.user #查看user资源的各种用法 puppet describe user #列出的资源管理接口,可自定义 Providers --------- aix, directoryservice, hpuxuseradd, ldap, pw, user_role_add, useradd, windows_adsi #示例 [root@node1 manifests]# vi user.pp user{'nginx': uid => 444, gid => 'nginx', system => true, ensure => present, } puppet apply -v --noop user.pp Notice: Compiled catalog for node1.localdomain in environment production in 0.20 seconds Info: Applying configuration version '1500561782' Notice: /Stage[main]/Main/User[nginx]/ensure: current_value absent, should be present (noop) Notice: Class[Main]: Would have triggered 'refresh' from 1 events Notice: Stage[main]: Would have triggered 'refresh' from 1 events Notice: Finished catalog run in 0.04 seconds [root@node1 manifests]# puppet apply -v user.pp Notice: Compiled catalog for node1.localdomain in environment production in 0.21 seconds Info: Applying configuration version '1500561816' Notice: /Stage[main]/Main/User[nginx]/ensure: created Notice: Finished catalog run in 0.07 seconds [root@node1 manifests]# tail -1 /etc/passwd nginx:x:444:995::/home/nginx:/bin/bash 关系源参数 before require notify subscribe四个元参数来定义资源间的相关性 资源定义有依赖关系,优先级 资源可以被定义,也可以被引用,资源的引用通过"Type['title']" 注意:首字母必须大写 #示例 vi redis.pp user{'redis': gid => 'redis', ensure => present, require => Group['redis'], } group{'redis': ensure => present, #before => User['redis'], } puppet apply -v -d --noop redis.pp Info: Applying configuration version '1500562662' Notice: /Stage[main]/Main/Group[redis]/ensure: current_value absent, should be present (noop) Debug: /Stage[main]/Main/Group[redis]: The container Class[Main] will propagate my refresh event Notice: /Stage[main]/Main/User[redis]/ensure: current_value absent, should be present (noop) Debug: /Stage[main]/Main/User[redis]: The container Class[Main] will propagate my refresh event Notice: Class[Main]: Would have triggered 'refresh' from 2 events Debug: Class[Main]: The container Stage[main] will propagate my refresh event Notice: Stage[main]: Would have triggered 'refresh' from 1 events [root@node1 manifests]# puppet apply -v -d redis.pp [root@node1 manifests]# grep -i "redis" /etc/passwd redis:x:1001:1001::/home/redis:/bin/bash3.package 3.package [root@node1 manifests]# puppet describe package package ======= Manage packages. Parameters ---------- - **ensure** What state the package should be in. `present` (also called `installed`), `absent`, `purged`, `held`, `latest`. - **install_options** Requires features install_options. - **instance** A read-only parameter set by the package. - **name** The package name. - **source** Where to find the package file. #示例1 vi package.pp package{'redis': ensure => latest, } [root@node1 manifests]# puppet apply -v -d --noop package.pp Notice: /Stage[main]/Main/Package[redis]/ensure: current_value absent, should be latest (noop) Debug: /Stage[main]/Main/Package[redis]: The container Class[Main] will propagate my refresh event Notice: Class[Main]: Would have triggered 'refresh' from 1 events Debug: Class[Main]: The container Stage[main] will propagate my refresh event Notice: Stage[main]: Would have triggered 'refresh' from 1 events #执行 [root@node1 manifests]# puppet apply -v package.pp Notice: Compiled catalog for node1.localdomain in environment production in 0.53 seconds Info: Applying configuration version '1500564098' Notice: /Stage[main]/Main/Package[redis]/ensure: created Notice: Finished catalog run in 2.93 seconds [root@node1 manifests]# rpm -q redis redis-3.2.3-1.el7.x86_64 #示例2 [root@node1 manifests]# vi jdk.pp package{'jdk': ensure => present, source => '/root/jdk-7u79-linux-x64.rpm', provider => rpm, } 4.service [root@node1 manifests]# puppet describe service service ======= Manage running services. Parameters ---------- - **binary** The path to the daemon. - **enable** Whether a service should be enabled to start at boot. - **ensure** Whether a service should be running. Valid values are `stopped` (also called `false`), `running` (also called `true`). - **flags** Specify a string of flags to pass to the startup script. Requires features flaggable. - **hasrestart** Specify that an init script has a `restart` command. the init script's `stop` and `start` commands will be used. Valid values are `true`, `false`. #对应这个脚本有没有restart操作 作用:如果命令有restart,就用restart,没有就stop,再start - **hasstatus** - **path** The search path for finding init scripts. #脚本搜索的路径: centos6:/etc/init centos7:/usr/lib/systemd/system/ - **start** Specify a *start* command manually. #手动定义start不用脚本的 - **restart** Specify a *restart* command manually. #通常定义reload操作 - **pattern** The pattern to search for in the process table. Providers --------- base, bsd, daemontools, debian, freebsd, gentoo, init, launchd, openbsd, openrc, openwrt, redhat, runit, service, smf, src, systemd, upstart, windows #示例 [root@node1 manifests]# puppet apply -v -d --noop service.pp Notice: /Stage[main]/Main/Service[redis]/ensure: current_value stopped, should be running (noop) Debug: /Stage[main]/Main/Service[redis]: The container Class[Main] will propagate my refresh event Info: /Stage[main]/Main/Service[redis]: Unscheduling refresh on Service[redis] Notice: Class[Main]: Would have triggered 'refresh' from 1 events Debug: Class[Main]: The container Stage[main] will propagate my refresh event Notice: Stage[main]: Would have triggered 'refresh' from 1 events [root@node1 manifests]# puppet apply -v -d service.pp Info: Applying configuration version '1500565381' Debug: Executing '/usr/bin/systemctl is-active redis' Debug: Executing '/usr/bin/systemctl is-enabled redis' Debug: Executing '/usr/bin/systemctl start redis' Debug: Executing '/usr/bin/systemctl is-enabled redis' Debug: Executing '/usr/bin/systemctl enable redis' Notice: /Stage[main]/Main/Service[redis]/ensure: ensure changed 'stopped' to 'running' [root@node1 manifests]# ss -tlnp | grep redis LISTEN 0 128 127.0.0.1:6379 *:* users:(("redis-server",pid=6817,fd=4)) #示例2 [root@node1 manifests]# vi service.pp package{'redis': ensure => present, } service{'redis': ensure => running, enable => true, require => Package['redis'], } 5.file [root@node1 manifests]# puppet describe file file ==== Manages files, including their content, ownership, and permissions. Parameters ---------- - **backup** - **checksum** The checksum type to use when determining whether to replace a file's contents. The default checksum type is md5. Valid values are `md5`, `md5lite`, `sha256`, `sha256lite`, `mtime`, `ctime`, `none`. - **content** The desired contents of a file, as a string.This attribute is mutually exclusive with `source` and `target`. - **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`. # Equivalent resources: file { "/etc/inetd.conf": ensure => "/etc/inet/inetd.conf", } file { "/etc/inetd.conf": ensure => link, target => "/etc/inet/inetd.conf", } - **force** Perform the file operation even if it will destroy one or more directories. - **group** Which group should own the file. - **links** How to handle links during file actions. During file copying, `follow` will copy the target file instead of the link, `manage` will copy the link itself, and `ignore` will just pass it by. - **mode** The desired permissions mode for the file, - **mtime** - **owner** The user to whom the file should belong. - **path** (*namevar*) The path to the file to manage. -**recurse** Whether to recursively manage the _contents_ of a directory. - **replace** - **source** A source file, which will be copied into place on the local system. - **source_permissions** Whether (and how) Puppet should copy owner, group, and mode permissions from the `source` to `file` resources when the permissions are not explicitly specified. Valid values are `use`, `use_when_creating`, and `ignore`: - **target** The target for creating a link. - **validate_cmd** A command for validating the file's syntax before replacing it. Example: file { '/etc/apache2/apache2.conf': content => 'example', validate_cmd => '/usr/sbin/apache2 -t -f %', } Providers --------- posix, windows #示例1 [root@node1 manifests]# cp /etc/redis.conf ./ [root@node1 manifests]# vi redis.conf bind 0.0.0.0 masterauth 123456 [root@node1 manifests]# ll /etc/redis.conf -rw-r--r--. 1 redis root 46730 Aug 5 2016 /etc/redis.conf [root@node1 manifests]# vi file1.pp [root@node1 manifests]# vi file1.pp file{'/etc/redis.conf': ensure => file, source => '/etc/puppet/manifests/redis.conf', owner => 'redis', group => 'root', mode => '0644', } [root@node1 manifests]# puppet apply -v -d --noop file1.pp [root@node1 manifests]# puppet apply -v -d --noop file1.pp Info: Applying configuration version '1500567458' Debug: Evicting cache entry for environment 'production' Debug: Caching environment 'production' (ttl = 0 sec) Info: Computing checksum on file /etc/redis.conf Debug: Evicting cache entry for environment 'production' Debug: Caching environment 'production' (ttl = 0 sec) Info: /Stage[main]/Main/File[/etc/redis.conf]: Filebucketed /etc/redis.conf to puppet with sum 910058e228c4ad556ffc0f473cef9323 [root@node1 manifests]# cat /etc/redis.conf | egrep -i "bind 0.0.0.0|masterauth 123456" bind 0.0.0.0 masterauth 123456 通知元参数 两个参数:通知和订阅,见名知意,很好理解。 notify,subscribe A notify B:B依赖于B,且A发生改变会通知B {notify => Type['B'],} B subscribe A :B依赖与A,B订阅A资源产生的事件 {subscribe => Type['B'],} 其中有特殊情况:链式依赖 #示例2 [root@node1 manifests]# vi service.pp #install redis package package{'redis': ensure => present, } #push source file to des file. file{'/etc/redis.conf': ensure => file, source => '/etc/puppet/manifests/redis.conf' require => Package['redis'], } #running redis server service{'redis': ensure => running, enable => true, require => Package['redis'], subscribe => File['/etc/redis.conf'], } [root@node1 manifests]# puppet apply -v -d --noop service.pp [root@node1 manifests]# puppet apply -v -d service.pp #示例3:修正版 A -> B 表示A before B;B ~> C 表示B notify C; [root@node1 manifests]# vi service.pp #install redis package package{'redis': ensure => present, } -> #push source file to des file. file{'/etc/redis.conf': ensure => file, source => '/etc/puppet/manifests/redis.conf', owner => 'redis', group => 'root', mode => '0644', } ~> #running redis server service{'redis': ensure => running, enable => true, } #或者还可以这样表示:Package['redis'] -> File['/etc/redis.conf'] ~> Service['redis'] #示例4:content用法 [root@node1 manifests]# vi test.pp file{'/tmp/test.txt': ensure => file, content => 'Hello World!', } [root@node1 manifests]# puppet apply -v test.pp #note:content also can be created by template. [root@node1 manifests]# puppet apply -v test.pp Notice: Compiled catalog for node1.localdomain in environment production in 0.16 seconds Info: Applying configuration version '1500569471' Notice: /Stage[main]/Main/File[/tmp/test.txt]/ensure: defined content as '{md5}ed076287532e86365e841e92bfc50d8c' Notice: Finished catalog run in 0.05 seconds [root@node1 manifests]# cat /tmp/test.txt Hello World! #示例6:link用法 [root@node1 manifests]# puppet apply -v link.pp Notice: Compiled catalog for node1.localdomain in environment production in 0.15 seconds Info: Applying configuration version '1500569692' Notice: /Stage[main]/Main/File[/tmp/test.link]/ensure: created Notice: Finished catalog run in 0.04 seconds [root@node1 manifests]# ll /tmp/test.link lrwxrwxrwx. 1 root root 13 Jul 21 00:54 /tmp/test.link -> /tmp/test.txt #示例5:递归创建目录 [root@node1 manifests]# vi mkdir.pp file{'/tmp/pam.d': ensure => directory, source => '/etc/pam.d', recurse => true, } #note: if source is not exist,which would create empty directory. [root@node1 manifests]# puppet apply -v mkdir.pp [root@node1 manifests]# ll /tmp/pam.d/ total 104 -rw-r--r--. 1 root root 192 Jul 21 00:59 chfn ... #(ps:DevOPs三个层次:bootstraping,configuration,command and control) 6.exec [root@node1 manifests]# puppet describe 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*. #任何能够在exec资源执行的命令必须能够重复执行,并且不产生危害,这就意味着,命令必须拥有幂等性。 Parameters ---------- - **command** (*namevar*) The actual command to execute. - **creates** A file to look for before running the command. #文件路径,当此路径的文件不存在,cmd就会执行 exec { "tar -xf /Volumes/nfs02/important.tar": cwd => "/var/tmp", creates => "/var/tmp/myfile", path => ["/usr/bin", "/usr/sbin"] } - **cwd** The directory from which to run the command. - **environment** Any additional environment variables you want to set for a command. - **group** The group to run the command as. - **logoutput** Whether to log command output in addition to logging the exit code. - **onlyif** If this parameter is set, then this `exec` will only run if the command has an exit code of 0. #只有这个命令运行成功才运行cmd。 For example: exec { "logrotate": path => "/usr/bin:/usr/sbin:/bin", onlyif => "test `du /var/log/messages | cut -f1` -gt 100000" } - **path** The search path used for command execution. - **refresh** How to refresh this command. #重新执行当前cmd的替代命令 - **refreshonly** The command should only be run as a refresh mechanism for when a dependent object is changed. #仅接收到订阅的资源的通知才运行cmd Valid values are `true`, `false`. - **returns** The expected exit code(s). - **timeout** The maximum time the command should take. - **tries** - **try_sleep** The time to sleep in seconds between 'tries'. - **umask** Sets the umask to be used while executing this command - **unless** If this parameter is set, then this `exec` will run unless the command has an exit code of 0. #如果这个命令运行失败就运行cmd - **user** The user to run the command as. Providers --------- posix, shell, windows #示例1:创建目录 [root@node1 manifests]# vi exec1.pp exec{'mkdir': command => 'mkdir /tmp/testdir', path => '/bin:/sbin:/usr/bin:/usr/sbin', creates => '/tmp/testdir', #directory not exist ,exec cmd. } [root@node1 manifests]# puppet apply -v exec1.pp Notice: Compiled catalog for node1.localdomain in environment production in 0.07 seconds Info: Applying configuration version '1500582762' Notice: /Stage[main]/Main/Exec[mkdir]/returns: executed successfully Notice: Finished catalog run in 0.04 seconds [root@node1 manifests]# ls /tmp/testdir/ -d /tmp/testdir/ #示例2:创建用户 [root@node1 manifests]# vi exec2.pp exec{'adduser': command => 'useradd -r mogilefs', path => '/bin:/sbin:/usr/bin:/usr/sbin', unless => 'id mogilefs', #unless id cmd success,exec comd. } [root@node1 manifests]# puppet apply -v exec2.pp Notice: Compiled catalog for node1.localdomain in environment production in 0.07 seconds Info: Applying configuration version '1500583160' Notice: /Stage[main]/Main/Exec[adduser]/returns: executed successfully Notice: Finished catalog run in 0.10 seconds [root@node1 manifests]# grep -i "mogilefs" /etc/passwd mogilefs:x:442:442::/home/mogilefs:/bin/bash [root@node1 manifests]# id mogilefs uid=442(mogilefs) gid=442(mogilefs) groups=442(mogilefs) #示例3 package{'httpd': ensure => latest, } ~> exec{'adduser': command => 'useradd -r httpd', path => '/bin:/sbin:/usr/bin:/usr/sbin', unless => 'id httpd', #unless id cmd success,exec comd. refreshonly => true, } [root@node1 manifests]# grep -i "httpd" /etc/passwd apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin httpd:x:442:442::/home/httpd:/bin/bash 7.cron [root@node1 manifests]# puppet describe cron cron ==== Installs and manages cron jobs. #cron资源必要要有一个周期性的属性 cron { logrotate: command => "/usr/sbin/logrotate", user => root, hour => ['2-4'], minute => '*/10' } Parameters ---------- - **command** The command to execute in the cron job. - **ensure** The basic property that the resource should be in.Valid values are `present`, `absent`. - **environment** Any environment settings associated with this cron job. - **hour** - **minute** - **month** - **monthday** - **name** The symbolic name of the cron job - **special** A special value such as 'reboot' or 'annually'. - **target** The name of the crontab file in which the cron job should be stored. #添加哪个用户的任务 - **user** - **weekday** #示例1 [root@node1 manifests]# vi cron1.pp cron{'synctime': command => '/usr/sbin/ntpdate 172.16.0.1 &> /dev/null', name => 'synctime from ntp server', minute => '*/30', } [root@node1 manifests]# puppet apply -v cron1.pp [root@node1 manifests]# crontab -l | grep '172.' */30 * * * * /usr/sbin/ntpdate 172.16.0.1 &> /dev/null 8.notify [root@node1 manifests]# puppet describe notify notify ====== Sends an arbitrary message to the agent run-time log. Parameters ---------- - **message** The message to be sent to the log. - **name** An arbitrary tag for your own reference; the name of the message. - **withpath** Whether to show the full object path. Defaults to false. Valid values are `true`, `false`. #示例 [root@node1 manifests]# puppet apply -v notify1.pp Notice: Compiled catalog for node1.localdomain in environment production in 0.03 seconds Info: Applying configuration version '1500584971' Notice: hi,you are welcome! Notice: /Stage[main]/Main/Notify[sayhi]/message: defined 'message' as 'hi,you are welcome!' Notice: Finished catalog run in 0.03 seconds
3.总结
主要介绍了核心类型资源的用法,核心类型资源包括:group,user,package,service,file,exec,cron,notify,总共8种资源的用法。 group定义属组相关用法,user定义属主用法,package定义程序包用法,service定义程序服务用法,file定义文件的用法,exec定义了自定义命令的用法,cron定义周期性任务的的用法,notify'定义信息通知的用法。
转载于:https://blog.51cto.com/huwho/1949369