Puppet simple application of Linux operation and maintenance Automation (I.)

Source: Internet
Author: User
Tags case statement echo command openssl

I. Overview of Pupper

Puppet, this is the current operation and maintenance of the mainstream automation tools, most operations managers have heard, or in use and in the consideration of use. Puppet can cooperate with Cobbler,puppet can also be implemented with Func operation and maintenance automation, simplification, complexity for the simple.

1. What is puppet

Puppet is a centralized configuration management system for Linux and UNIX platforms, using the Ruby language to manage profiles, users, cron tasks, packages, system services, and more. Puppet these system entities as resources, Puppet's design objective is to simplify the management of these resources and to properly handle the dependencies between resources.

Syntax for 2.puppet

Since Puppet is written by Ruby, as Ruby syntax is very similar, the introduction to Ruby: See http://ruby-lang.org

What resources 3.puppet can manage:

Able to manage file (files), User (users), group (group), package (packages), Mount (Mount), schedule and cron (scheduled Tasks), Service (services), tidy (cleanup), Yumrepo (Yum warehouse), Sshkey (SSH authentication) and other common resources.

4.Puppet Mode of operation

Puppet is a C/S Architecture Configuration Management tool that installs the Puppet-server software package (known as puppetmaster) on a central server. Install the puppet client software (known as puppetclient) on the target host that needs to be managed.

When the client connects on puppetmaster, the configuration file defined on the puppetmaster is compiled and then run on the client. Each client, by default, communicates with the server every half hour, confirming the update of the configuration information. If there is new configuration information or the configuration information has changed, the configuration will be recompiled and published to each client for execution. You can also proactively trigger an update of configuration information on the server, forcing each client to configure it. If the configuration information for the client is changed, it can be corrected from the server for the original configuration.

Second, single-machine application of puppet

1, installation Puppet

Download the installation package folder

Puppet installation Package

[[Email protected] ~]# CD 2.7.25/[[email protected] 2.7.25]# yum-y install facter-1.7.3-1.el6.x86_64.rpm puppet-2.7.25-1 . el6.noarch.rpm

2, Puppet common resources

2.1 How to define Resources

A resource is a base unit that puppet used to model system configurations, each of which describes system properties from an angle, such as a package that must be installed or a user must be removed, and, in puppet, the code that is used to complete such functionality is also the "resource Declaration"


Type {' title ':

Atttibue = value,


Note: The file of the resource is unified with the. PP End

When defined, the resource type must use lowercase letters, and the resource name is only a string, but requires that the middle of the same type must be unique

2.2. Package Resources: Puppet management software packages

Puppet support for use with Package Manager: Yum,rpm,apt,prots,gem,msi,dpkg,pkg

Common parameters:

    • Ensure: The target State of the package, with values present (installed), absent (not present), purged, held, latest

    • Name: The names of the resources, that is, the package name, can be omitted, if omitted, will inherit the value of the title

    • Provide: Package Manager

    • Source: Specify Package file path

    • Install_options: Installation options, most commonly by Inatalldir to create the installation directory

2.3. Service resource: Used to define the status of the service

Common parameters

    • Ensure: The amount of the service's target state, with a value of true (running) and false (stopped)

    • Enable: Whether the boot starts automatically, the value has true and false

    • Name: The service name can be omitted, and if omitted, the value of the title will be inherited

    • Path: Service script path, default to/etc/init.d/

    • Start: Custom Start command

    • STOP: Customizing the Close command

    • Restart: Custom Restart command

    • Status: Custom state


[Email protected] tmp]# vim test1.pp//added as follows: package {' Nginx ':        ensure +  present,}service {' Nginx ':         ensure = True,         enable = True,}

Note: This resource will automatically install Nginx and enable it to start immediately, boot

You can use this command to check the syntax:

[Email protected] tmp]# puppet parser validate/tmp/test1.pp

How to use this command to apply locally:

Puppet Apply Test1.pp

2.4. File Resources

This resource can manage files, directories, soft links, generate file contents, manage file permissions, properties, or download files from the Source property to a specified location; Get a directory by Recurse property

Common parameters:

      Ensuce: Target State, value absent, present, file, and directory.

    • Backup: Backing up files with Filebacket resources, typically the name of the Filebucket resource

    • Content: File content, generated in three ways (Content,source, Target), the three are mutually exclusive to each other,

      content when generating properties using template templates, such as: content   =>template (' module_name/template_file_name ')

    • Source: Download the file to local by the developed URL, get the file format: puppet:/// Modules/module_name/file_names

    • Target: Specify a target for symbolic links

    • Links: The file is a symbolic connection with a value of "Follow", " Manage "

    • Path: File path, double quotes must be used

    • Mode: Define permissions, typically 8 digits

    • Owner: The owner of the definition file

    • Group: Define the genus of the file

    • Force: Enforce delete files, links or directories, only for ensure to absent

    • Purge: Clears files that exist in the specified directory but are not defined in the resource

    • Resurce: directory recursion, value is True,false,inf,remote

    • Replace: Replace, the file that exists locally does not perform a substitution with the contents of the file specified in the resource, and defaults to no


[Email protected] tmp]# vim test2.pp//is added as follows: file {' abc.txt ':       ensure  = present,       content = ' Hello Puppet ',       path    = "/tmp/abc2.txt",}file {' fstab.symbolic ':       ensure = present,       target = + "/ Etc/fstab ",       path   ="/tmp/fstab.symbolic ",       links  = follow,}

Note: This resource generates the Abc2.txt file and fstab.symbolic this linked file.

2.5. EXEC Resources

Execute commands, usually used when you have to, use them sparingly, often to complete functions that puppet cannot do itself

Common parameters:

    • Command: The full path of the command file to be executed through the

    • Path: Command Search Path

    • Group: Groups that execute a command

    • User: Users executing the command

    • onlyif:0 that executes this command only if the command's status returns a value of 0 o'clock

    • Refresh: When you define notifications for other resources that you accept, you re-execute this command

    • Refreshonly: Triggered only when a dependent resource has changed

    • Tries: Number of attempts, default = 1

    • Try_sleep: Time interval between multiple attempts


[[email protected] tmp]# vim test3.pp//added as follows: exec {' echo command ':       command = ' echo ' Hello puppet ' >>/tmp/com Mand.txt ',       path    = '/bin:/sbin:/usr/bin:/usr/sbin ',       refreshonly = True,    }      exec {' mkdir ' :       command = ' mktemp/tmp/tmp. XXXX ',       path    = '/bin:/sbin:/usr/bin:/usr/sbin ',}

Note: This resource will echo out the message and create a random file

[Email protected] tmp]# vim test4.pp//is added as follows: file {'/tmp/test4.txt ':       ensure  = file,       content = " Hello puppet ",       notify  = exec[' monitor ']}exec {' monitor ':        command   = ' echo '/tmp/test4.txt Changed ">>/tmp/monitor.txt ',       # subscribe = file['/tmp/test4.txt '],        path      = '/bin:/sbin:/ Usr/sbin:/usr/bin ',       refreshonly = True,}

Note: This resource creates a Test4.txt file, and when the content of this file changes, the output information

2.6. Group resources: User groups on the management system

Common parameters:

    • Ensure: Target status, Present,absent

    • Name: Group name

    • Gid:gid

    • System: Systems Group

2.7. User: Manage Users

Common parameters:

    • Ensure: Target status, Present,absent

    • Name: User Name

    • UID: User uid

    • System: Systems User

    • Home: User home Directory

    • Shell: User Default Shell

    • GID: User's GID

    • Password: password, use password after encryption

    • Magagehome: Whether to create home directory, default to False


[Email protected] tmp]# vim test5.pp//added as follows: Group {' TESTGRP ':        ensure = present,        gid    = 1001,}user {' TestUser ':         ensure = present,         gid    = 1001,         uid    = 1001,         home   =/home/ Test ',         shell  = '/bin/bash ',         password = ' $1$a8edbf1f$u4bv1eahjeafyxwidyxkn ',         Managehome = True,}

Note: This resource creates a testuser user, and the password can be generated using this command:

[email protected] tmp]# OpenSSL passwd-1-salt ' OpenSSL rand-hex 4 '

2.8. Cron Resources: Define recurring tasks

Common Properties:

    • Ensure: Target status, Present,absent

    • Command: Commands or scripts

    • Environment: Run-time environment variables

    • Hour: Hours

    • Mouth: Month

    • MonthDay: Sun

    • Weekday: Zhou

    • minute: Min

    • Name: Names

    • User: Default is root

2.9. Notify resources: Debug output

Common parameters

    • Message: Information

    • Name: Information names


[Email protected] tmp]# vim test6.pp//is added as follows: file {'/tmp/test4.txt ':       ensure  = file,       content = " Hello puppet ",       notify  = notify[' notice '],}notify {' notice ': message = '/tmp/test4.txt changed '}

3. Puppet variable

The variable name of the puppet begins with "$", the assignment operator is "=", the value of the variable is "", or nothing is written.

The puppet variable can accept the data type:

    • Boolean: True and False, cannot be quoted, the IF statement's test condition and comparison expression return a Boolean value, and other data types can be automatically converted to Boolean, such as an empty string of false, etc.

    • UNDEF: The value type of a variable that is never declared is undef, or you can manually assign a undef value to a variable, that is, to use the unquoted undef string directly

    • Character type: An unstructured text string that can be used in quotation marks or not. Variables in single quotes are not replaced, and variable substitution is possible in double quotes, and character types also support the use of the transfer characters

    • Numeric: Can be an integer or a floating-point number, however, Puppe is treated numerically as a numeric value only in numeric context, and is treated as a character in all other clean-up

    • Array: The array value is a comma-separated list of items in brackets "[]", followed by a comma after the last item; Yuan in an array can be considered as any available data type, including hash or other arrays, the group index is an integer starting at 0, or you can use a negative index

    • Hash: That is, the foreign key value data type, the key and the value is separated by "= =", the key value pair is defined in "{}", separated by commas with each other, its keyed character data, and the value can be any data type supported by puppet, the data element of the hash type should be indexed using "key"

    • Regular Expressions: Non-standard data types belonging to puppet, cannot be assigned to variables, can only be used in a limited number of places to receive regular expressions, that is, accept the location of the "=~" and "!~" matching operators, usually including selector in the case statement, where the node name matches, They cannot be passed to a function or defined for a resource property

Facter variable: Can be viewed through facter

Built-in variables:

Agent side: $environment, $clientcert, $clentbversion

Server side: $servername, $serverip, $serverversion

Regular expressions in puppet support the use of (? <enabled option>:<sunpattern>) and (?-<disabled option>:<sunpattern> ) Two special symbols,

As shown in the following example, the option "I (Ignore character case)" is enabled when a regular expression match is made, but the use of "m (as a newline character)" and "X (whitespace characters and annotations in ignore mode)" are not supported

$packages = $operatingsystem? {      /(? i-mx:ubuntu|debian)/        = ' apache2 ',      /(? i-mx:centos|fedora|redhat)/= ' httpd ',    }

4, the Puppet judgment statement

There are three kinds of judgment statements of puppet, namely If,case,selector

    • Example of an IF statement:

[Email protected] tmp]# vim test8.pp//added as follows: if $operatingsystem = = ' CentOS ' {       notify {' CentOS ': message = ' Welcome To Centos linux "}}elsif $operatingsystem = = ' RedHat ' {       notify {' RedHat ': message =" Welcome to RedHat Linux "}}elsi F $operatingsystem = = ' Fedora ' {       notify {' Fedora ': message = ' Welcome to Fedora Linux '}}else {      notify {' Unknow ' : Message = "Unknown operating system"}}if $operatingsystem =~/^ (? I-mx: (Centos|redhat|fedora))/{      Notice (" Welcome to Linux System ")}

Note: This resource contains the IF single branch statement and the multi-branch statement, the effect is the same

    • Selector Statement Example:

[[email protected] tmp]# vim test9.pp//added as follows: $webserver = $operatingsystem? {   /^ (? i-mx:centos|fedora|redhat)/= ' httpd ',  /^ (? i-mx:ubuntu|debian)/         = ' apache2 ',}$ Webprovider = $operatingsystem? {   /^ (? i-mx:centos|fedora|redhat)/= ' Yum ',  /^ (? i-mx:ubuntu|debian)/         ' apt ',}package {"$ Webserver ":      ensure =>present,      Provider = $webprovider,}

    • Example Case statement:

[[email protected] tmp]# vim test10.pp//added as follows: Case $operatingsystem {            /^ (? i-mx:redhat|centos|fedora)/: {package {' HTTPd ': ensure = present, Provider = Yum,}}            /^ (? i-mx:ubuntu|debian)/: {package {' apache2 ': ensure = Pre Sent, Provider = Apt,}}            default: {notify {' notice ': message = ' unknown system. ',}}        }

Well, to this, puppet installation and single-machine application has been introduced, next time we introduce under the C/S mode of the puppet application!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.