lang110 发表于 2018-8-1 13:27:00

puppet基础篇(练习篇)

核心类型:  
                group: 组
  user:用户
  packge:程序包
  service:服务
  file:文件
  exec:执行自定义命令,要求幂等
  cron:周期性任务计划
  notify:通知###资源定义
  通过资源类型的属性赋值来实现资源定义,这也称为资源类型实例化。定义资源实例化的文件即清单:manifest
  ###属性:attribute
  资源属性中三个个特殊属性(几乎所有的资源中都有)
  namevar,可简写为name,描述资源的名字
  ensure,描述资源的目标状态
  provider,资源的管理接口
  语法;
  type {'title':
  attribute1 => value1,
  atrribute2=> value2,
  ……
  }
  
      #创建清单的目录
  # mkdir manifests
  # cd manifests/
  

  ###资源类型
  1.group
  group{'nginx':
  ensure=>present,
  name    =>'nginx',
  system=>true,
  }
  #干跑模式
  # 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/Group/ensure: current_value absent, should be present (noop)
  Notice: Class: Would have triggered 'refresh' from 1 eventsNotice: Stage: Would have triggered 'refresh' from 1 events
  Notice: Finished catalog run in 0.04 seconds
  #执行
  # puppet apply --verbose --debugfirst.pp
  Info: Applying configuration version '1500560157'
  Debug: Executing '/usr/sbin/groupadd -r nginx'
  Notice: /Stage/Main/Group/ensure: createdNotice: Finished catalog run in 0.08 seconds
  #查看
  # 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
  #示例
  # 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/User/ensure: current_value absent, should be present (noop)
  Notice: Class: Would have triggered 'refresh' from 1 events
  Notice: Stage: Would have triggered 'refresh' from 1 events
  Notice: Finished catalog run in 0.04 seconds
  

  # puppet apply -vuser.pp
  Notice: Compiled catalog for node1.localdomain in environment production in 0.21 seconds
  Info: Applying configuration version '1500561816'
  Notice: /Stage/Main/User/ensure: createdNotice: Finished catalog run in 0.07 seconds
  

  # 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/Group/ensure: current_value absent, should be present (noop)
  Debug: /Stage/Main/Group: The container Class will propagate my refresh event
  Notice: /Stage/Main/User/ensure: current_value absent, should be present (noop)
  Debug: /Stage/Main/User: The container Class will propagate my refresh eventNotice: Class: Would have triggered 'refresh' from 2 events
  Debug: Class: The container Stage will propagate my refresh eventNotice: Stage: Would have triggered 'refresh' from 1 events
  

  # puppet apply -v -dredis.pp
  

  # grep -i "redis" /etc/passwd
  redis:x:1001:1001::/home/redis:/bin/bash3.package
  

  3.package
  # 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,
  
    }
  

  # puppet apply -v -d --noop package.pp
  Notice: /Stage/Main/Package/ensure: current_value absent, should be latest (noop)
  Debug: /Stage/Main/Package: The container Class will propagate my refresh event
  Notice: Class: Would have triggered 'refresh' from 1 events
  Debug: Class: The container Stage will propagate my refresh event
  Notice: Stage: Would have triggered 'refresh' from 1 events
  #执行
  # puppet apply -vpackage.pp
  Notice: Compiled catalog for node1.localdomain in environment production in 0.53 seconds
  Info: Applying configuration version '1500564098'
  Notice: /Stage/Main/Package/ensure: created
  Notice: Finished catalog run in 2.93 seconds
  

  # rpm -q redis
  redis-3.2.3-1.el7.x86_64
  #示例2
  # vi jdk.pp
  

  package{'jdk':
  ensure      =>present,
  source      =>'/root/jdk-7u79-linux-x64.rpm',
  provider    =>rpm,
  }
  4.service
  # 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
  

  #示例
  # puppet apply -v -d --noop service.pp
  

  Notice: /Stage/Main/Service/ensure: current_value stopped, should be running (noop)
  Debug: /Stage/Main/Service: The container Class will propagate my refresh event
  Info: /Stage/Main/Service: Unscheduling refresh on Service
  Notice: Class: Would have triggered 'refresh' from 1 events
  Debug: Class: The container Stage will propagate my refresh event
  Notice: Stage: Would have triggered 'refresh' from 1 events
  

  # 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/Service/ensure: ensure changed 'stopped' to 'running'
  

  # ss -tlnp | grep redis
  LISTEN   0      128    127.0.0.1:6379                     *:*                   users:(("redis-server",pid=6817,fd=4))
  

  #示例2
  # vi service.pp
  

  package{'redis':
  ensure      =>present,
  }
  

  service{'redis':
  ensure      =>running,
  enable      =>true,
  require   =>Package['redis'],
  }
  

  5.file
  # 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
  # cp /etc/redis.conf ./
  # vi redis.conf
  bind 0.0.0.0
  masterauth 123456
  

  # ll /etc/redis.conf
  -rw-r--r--. 1 redis root 46730 Aug52016 /etc/redis.conf
  

  # vi file1.pp
  

  # vi file1.pp
  

  file{'/etc/redis.conf':
  ensure      =>file,
  source      =>'/etc/puppet/manifests/redis.conf',
  owner       =>'redis',
  group       =>'root',
  mode      =>'0644',
  }
  

  # puppet apply -v -d --noop file1.pp
  

  # 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/File: Filebucketed /etc/redis.conf to puppet with sum 910058e228c4ad556ffc0f473cef9323
  

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

  # puppet apply -v -d --noop service.pp
  # puppet apply -v -d service.pp
  

  #示例3:修正版 A -> B 表示A before B;B ~> C 表示B notify C;
  # 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用法
  # vi test.pp
  

  file{'/tmp/test.txt':
  ensure=>file,
  content =>'Hello World!',
  }
  

  # puppet apply -v test.pp
  

  #note:content also can be created by template.
  # 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/File/ensure: defined content as '{md5}ed076287532e86365e841e92bfc50d8c'
  Notice: Finished catalog run in 0.05 seconds
  

  # cat /tmp/test.txt
  Hello World!
  

  #示例6:link用法
  # 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/File/ensure: created
  Notice: Finished catalog run in 0.04 seconds
  

  # ll /tmp/test.link
  lrwxrwxrwx. 1 root root 13 Jul 21 00:54 /tmp/test.link -> /tmp/test.txt
  #示例5:递归创建目录
  # vi mkdir.pp
  

  file{'/tmp/pam.d':
  ensure      =>directory,
  source      =>'/etc/pam.d',
  recurse    =>true,
  }#note: if source isnot exist,which would create empty directory.
  

  # puppet apply -v mkdir.pp
  

  # 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
  # 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:创建目录
  

  

  

  # vi exec1.pp
  

  exec{'mkdir':
  command   =>'mkdir /tmp/testdir',
  path      =>'/bin:/sbin:/usr/bin:/usr/sbin',
  creates   =>'/tmp/testdir',#directory not exist ,exec cmd.
  }
  

  

  # 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/Exec/returns: executed successfully
  Notice: Finished catalog run in 0.04 seconds
  

  # ls /tmp/testdir/ -d
  /tmp/testdir/
  #示例2:创建用户
  # 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.
  }
  

  # 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/Exec/returns: executed successfully
  Notice: Finished catalog run in 0.10 seconds
  

  # grep -i "mogilefs" /etc/passwd
  mogilefs:x:442:442::/home/mogilefs:/bin/bash
  

  # 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,
  }
  

  # 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
  

  # 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
  # vi cron1.pp
  

  cron{'synctime':
  command   =>'/usr/sbin/ntpdate 172.16.0.1 &> /dev/null',
  name      =>'synctime from ntp server',
  minute      =>'*/30',
  }
  

  # puppet apply -v cron1.pp
  # crontab -l | grep '172.'
  */30 * * * * /usr/sbin/ntpdate 172.16.0.1 &> /dev/null
  

  8.notify
  # 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`.
  

  #示例
  # 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/Notify/message: defined 'message' as 'hi,you are welcome!'
  Notice: Finished catalog run in 0.03 seconds
页: [1]
查看完整版本: puppet基础篇(练习篇)