The playbook of 3.3 ansible

Source: Internet
Author: User

Playbook

1 Playbook is a list consisting of one or more "play"
The main function of 2 play is to dress up a pre-merged host into a role defined in advance by a task in ansible. Fundamentally, the so-called task is nothing more than a module that calls Ansible. Organize multiple play in a single playbook, which allows them to join together to sing a drama with a pre-programmed mechanism
3 Playbook written in Yaml language

Introduction to YAML syntax

List: Lists, all of whose elements begin with "-"
Example

A List of Tasty fruits

    • Apple
    • Orange
    • Strawberry
    • Mangoyaml Introduction

      1 Yaml is a highly readable format for expressing data sequences. Yaml references a variety of other languages, including XML, C, Python, Perl, and e-mail format RFC2822. Clark Evans published the language for the first time in 2001, and Ingy d?t net and Oren Ben-kiki were also co-designers of the language.
      2 Yaml Ain ' t Markup Language, that is, YAML is not XML. However, in developing this language, Yaml's meaning is actually: "Yet another Markup Language" (still a markup language)

Characteristics

Good readability of Yaml
The interactivity between Yaml and scripting language is good
YAML uses the data type of the implementation language
YAML has a consistent information model.
Yaml is easy to implement
YAML can process based on streams
Yaml has strong expressive ability and good extensibility
For more content and specifications see http://www.yaml.org

Introduction to YAML syntax

1 in a single file, multiple files can be distinguished by three consecutive hyphen (-). In addition, there is a selection of three consecutive points (...) Used to indicate the end of a file
2 times the line begins to write the contents of the playbook normally, it is generally suggested that the Playbook function
3 Comment Code with # #
4 indentation must be uniform, not space and tab mix
5 The level of indentation must also be consistent, the same indentation represents the same level, the level of the program discriminant configuration is achieved by indentation combined with a newline
6 Yaml file contents are consistent with the Linux system case-sensitivity, are case-sensitive, and the k/v values are case-insensitive
The value of 7 k/v can be written in the same line or in a newline. Peer use: Separate
8 V is a string, but another list
91 full code block functionality requires minimum elements to include Name:task
101 name can consist of only one task
Yaml file extension is usually yml or Yaml
Dictionary: A dictionary, usually consisting of multiple keys and value

Example:
An Employee record
{name:example Developer, job:developer, Skill:elite}

Yaml's syntax is similar to other high-order languages, and it can simply express data structures such as lists, hash lists, and scalars. Its structure (Structure) is shown by a space, the items in the sequence (Sequence) are represented by "-", and the key-value pairs in the map are separated by ":".

Display columns:
Name:john Smith
age:41
Gender:male
Spouse:
Name:jane Smith
Age:37
Gender:female
Children:

    • Name:jimmy Smith
      Age:17
      Gender:male
    • Name:jenny Smith
      Age 13
      Gender:female
Playbook Core Elements

1 List of remote hosts executed by the hosts
2 Tasks Task Set
3 Varniables built-in variables or custom variables are called in Playbook
4 Templates templates to replace variables in template files and implement some simple logic files
5 handlers and notity are used in conjunction, the action triggered by a specific condition, satisfies the condition to execute, otherwise does not execute
6 tags tag specifies a task execution that selects some code in the run playbook. The ansible is idempotent, so it will automatically skip the unchanged parts, even though some code will be very long to test that it really hasn't changed. At this point, if you are sure that it has not changed, you can skip these code snippets through tags

Ansible-playbook–t Tagsname useradd.yml

Example

[Email protected] ansible]# vim test.yml

    • Hosts:cen7 the host to execute
      Remote_user:root with which user to execute

      Tasks: Task Set

      • Name:install Package a task to have a name
        YUM:NAME=HTTPD called modules, and parameters
      • Name:start Service
        SERVICE:NAME=HTTPD state=started Enabled=yes
View the list of hosts executed in playbook

[Email protected] ansible]# Ansible-playbook test.yml--list-host

Playbook:test.yml

Play #1 (CEN7): Cen7 TAGS: []
Pattern: [u ' cen7 ']
Hosts (2):
192.168.27.101
192.168.27.102

See what tasks are in Playbook

error! You must specify a playbook file to run
[Email protected] ansible]# Ansible-playbook test.yml--list-tasks

Playbook:test.yml

Play #1 (CEN7): Cen7 TAGS: []
Tasks
Install package TAGS: []
Start service TAGS: []

A playbook recommended to write only one play, of course you can write multiple play

Experiment

1 Install the HTTP service and set it to boot, and change the port to 8080 port, turn on the service, write a playbook
2 first install an HTTP service on your own computer, and modify the configuration file, and then copy the configuration file to the remote host, start the service, all the hosts here are CENTOS7, different system versions of the HTTP configuration file is not the same, so the same version

    • Hosts:cen7
      Remote_user:root

      Tasks

      • Name:isntall httpd
        Yum:name=httpd
      • Name:copy Config httpd
        Copy:src=/app/httpd.conf Dest=/etc/httpd/conf/backup=yes
      • Name:start httpd
        SERVICE:NAME=HTTPD state=started Enabled=yes
When we want to change the configuration file to port 80, if we re-execute the above playbook will not be changed, because it just defines the start service, so we have to use the handlers condition
    • Hosts:cen7
      Remote_user:root

      Tasks

      • Name:isntall httpd
        Yum:name=httpd
      • Name:copy Config httpd
        Copy:src=/app/httpd.conf Dest=/etc/httpd/conf/backup=yes
        Notify:restart HTTPD performs the name task specified by notify when copy changes
      • Name:start httpd
        SERVICE:NAME=HTTPD state=started Enabled=yes

      Handlers:handlers is a special task and can write multiple tasks.

      • Name:restart httpd
        SERVICE:NAME=HTTPD state=restarted
When the first execution of this playbook is executed sequentially, the handlers is not triggered because the first packet is not loaded, but when the second execution starts execution of the handlers, the corresponding handlers task is executed when the copy command execution results are changed.

Playbook Basic Components

Hosts
The purpose of each play in playbook is to have some or some hosts perform tasks as a specified user. Hosts are used to specify the host to perform the specified tasks, which must be defined in the host manifest
Can be the following form

Bash
One.example.com
One.example.com:two.example.com
192.168.1.50
192.168.1.*

Websrvs:dbsrvs Two-group set
Websrvs:&dbsrvs intersection of two groups
Webservers:!phoenix in Websrvs Group, but not in Dbsrvs group
Example:-Hosts:websrvs:dbsrvs

Remote_user: Can be used in host and task. You can also perform tasks on a remote host by specifying that it is sudo, which can be used for play global or a task, and even for users who switch when sudo is specified with Sudo_user.
    • Hosts:websrvs
      Remote_user:root
      Tasks
      • Name:test Connection
        Ping:
        remote_user:magedu
        Sudo:yes default sudo is root
        Sudo_user:wang sudo to Wang
Task List and action

The main part of 1 play is the task list. The tasks in the task list are executed sequentially, one by one, on all hosts specified in the hosts, that is, the first task is completed on all hosts before the second begins. When a playbook is run from the bottom, if an error occurs halfway through, all the executed tasks are rolled back, so you can do it again after correcting playbook
The purpose of the 2 task is to execute the module with the specified parameters, and the variables can be used in the module parameters. Module execution is idempotent, which means that multiple executions are safe because the results are consistent
Each task should have its name, which is used to output the execution results of the playbook, suggesting that its contents describe the task execution steps as clearly as possible. If name is not provided, the result of the action is used for the output

Tasks: Task List

Format:
(1) Action:module arguments
(2) Module:arguments recommended use

Example
Tasks

    • Name:disable SELinux
      Command:/sbin/setenforce 0
If the exit code for a command or script is not zero, you can substitute the following
tasks:
    • Name:run This command and ignore the result
      Shell:/usr/bin/somecommand | | /bin/true
Or use Ignore_errors to ignore error messages
tasks:
    • Name:run This command and ignore the result
      Shell:/usr/bin/somecommand
      Ignore_errors:true
Run Playbook

How to Run Playbook

Ansible-playbook <filename.yml> ... [Options]

Common options
–check only detects changes that may occur, but does not actually perform the operation
–list-hosts List the hosts running the task
–limit host list is only performed for hosts in the host list
-V Show procedure-VV-VVV more details

    • Example
      Ansible-playbook file.yml--check Detection only
      Ansible-playbook file.yml
      Ansible-playbook file.yml--limit Websrvs

Example 1, limited to a specific host execution, is not so the host executes
[Email protected] app]# Ansible-playbook httpd.yml--limit 192.168.27.101
Not all hosts are executed for 101 hosts only

Playbook VS Shellscriptsshell Script

#!/bin/bash

Installing Apache

Yum Install--quiet-y httpd

Copying a configuration file

Cp/path/to/config/httpd.conf
/etc/httpd/conf/httpd.conf
Cp/path/to/httpd-vhosts.conf
/etc/httpd/conf/httpd-vhosts.conf

Start Apache, and set boot up

Service httpd Start
Chkconfig httpd on

Playbook Definition
    • Hosts:all
      Tasks
    • Name: "Install Apache"
      Command:yum install-q-y httpd
    • Name: "Copy configuration File"
      Command:cp/tmp/httpd.conf/etc/httpd/conf/httpd.conf
      Command:cp/tmp/httpd-vhosts.conf/etc/httpd/conf/httpd-vhosts.conf
    • Name: "Start Apache, and set boot start"
      SERVICE:NAME=HTTPD state=started Enabled=yes

      Example
      Example: System.yml

      -hosts:all
      Remote_user:root
      Tasks

      • name:create MySQL User
        User:name=mysql System=yes uid=36
      • Name:create a group
        GROUP:NAME=HTTPD System=yes

      Example: Httpd.yml

      • Hosts:websrvs
        Remote_user:root
        Tasks
      • Name:install httpd
        YUM:NAME=HTTPD state=present
      • Name:install Configure file
        Copy:src=files/httpd.conf dest=/etc/httpd/conf/
        • Name:start Service
          SERVICE:NAME=HTTPD state=started Enabled=yeshandlers and notify with trigger conditions

Handlers
is a task list, and these tasks are not inherently different from the aforementioned tasks, and are used to take action when the resource of interest changes.
Notify this action can be used to be triggered at the end of each play, which prevents multiple changes to occur each time the specified action is performed, only once all changes have been completed. The operations listed in notify are called Handler, which is called the actions defined in handler in notify

Playbook in handlers use
    • Hosts:websrvs
      Remote_user:root
      Tasks
      • Name:install httpd
        YUM:NAME=HTTPD state=present
      • Name:install Configure file
        Copy:src=files/httpd.conf dest=/etc/httpd/conf/
        Notify:restart httpd
      • Name:ensure Apache is running
        SERVICE:NAME=HTTPD state=started Enabled=yes
        Handlers:
      • Name:restart httpd
        SERVICE:NAME=HTTPD status=restarted

Example

    • Hosts:websrvs
      Remote_user:root
      Tasks
      • Name:add Group Nginx
        Tags:user
        User:name=nginx state=present
      • Name:add User Nginx
        User:name=nginx state=present Group=nginx
      • Name:install Nginx
        Yum:name=nginx state=present
      • Name:config
        Copy:src=/root/config.txt dest=/etc/nginx/nginx.conf
        Notify
        • Restart Nginx
        • Check Nginx Process
          Handlers:
      • Name:restart Nginx
        Service:name=nginx state=restarted Enabled=yes
      • Name:check Nginx Process
        shell:killall-0 nginx >/tmp/nginx.log
Playbook in the use of tags, from the script to pick out tags on behalf of the task, only perform this, the other does not perform

Tage can have the same name.
Example: Httpd.yml

    • Hosts:websrvs
      Remote_user:root
      Tasks
      • Name:install httpd
        YUM:NAME=HTTPD state=present
      • Name:install Configure file
        Copy:src=files/httpd.conf dest=/etc/httpd/conf/
        Tags:conf
      • Name:start httpd Service
        Tags:service
        SERVICE:NAME=HTTPD state=started Enabled=yes

[Email protected] app]# ansible-playbook-t conf,service httpd.yml

You can start multiple tags tags at once. Plus-T or –tags

Variables used in playbook

Variable name: can only be composed of letters, numbers and underscores, and can only start with a letter
Variable Source:
1 ansible Setup Facts All variables of the remote host can be called directly
2 defined in/etc/ansible/hosts
Normal variable: Host group in a separate definition, priority higher than public variables
Public (group) variables: Define uniform variables for all hosts in the host group
3 Assigning variables by command line with highest precedence
Ansible-playbook–e Varname=value
4 defined in Playbook
Bash
Vars:</li>
<li>var1:value1</li>
<li>var2:value2

5 defined in role
Use the Setup module to view all the built-in variables of the machine

Ansible cen7-m Setup

You can also search for variables with the filter parameter, which supports wildcard characters

[Email protected] app]# ansible cen7-m setup-a ' filter=hostname
192.168.27.102 | SUCCESS = {
"Ansible_facts": {
"Ansible_hostname": "g102"
},
"Changed": false
}
192.168.27.101 | SUCCESS = {
"Ansible_facts": {
"Ansible_hostname": "G101"
},
"Changed": false
}
[Email protected] app]# ansible cen7-m setup-a ' filter=nodename
192.168.27.101 | SUCCESS = {
"Ansible_facts": {
"Ansible_nodename": "G101.com"
},
"Changed": false
}
192.168.27.102 | SUCCESS = {
"Ansible_facts": {
"Ansible_nodename": "G102.com"
},
"Changed": false
}
[Email protected] app]# ansible cen7-m setup-a ' filter=FQDN
192.168.27.102 | SUCCESS = {
"Ansible_facts": {
"Ansible_fqdn": "G102.com"
},
"Changed": false
}
192.168.27.101 | SUCCESS = {
"Ansible_facts": {
"Ansible_fqdn": "G101.com"
},
"Changed": false
}
Best to write the full name
You can check the IP address.
CT, RAW, meta
[Email protected] app]# ansible cen7-m setup-a ' filter=Addr
192.168.27.102 | SUCCESS = {
"Ansible_facts": {
"Ansible_all_ipv4_addresses": [
"192.168.27.102"
],
"Ansible_all_ipv6_addresses": [
"FE80::20C:29FF:FE8B:F0DD"
]
},
"Changed": false
}
192.168.27.101 | SUCCESS = {
"Ansible_facts": {
"Ansible_all_ipv4_addresses": [
"192.168.27.101"
],
"Ansible_all_ipv6_addresses": [
"Fe80::20c:29ff:fec3:887f"
]
},
"Changed": false
}

Variables used in playbook

Variable naming
Variable names can only consist of letters, numbers, and underscores, and can only start with a letter
Variable definition: key=value
Example: http_port=80
Variable Invocation method:
The variable is called through {{variable_name}}, and there must be a space before and after the variable name, sometimes with "{{variable_name}}" to take effect

ansible-playbook –e 选项指定

Ansible-playbook test.yml-e "Hosts=www user=mageedu"

Example 1:var.yml

    • Hosts:websrvs
      Remote_user:root
      Tasks
      • Name:install Package
        yum:name={{Pkname}} state=present
ANSIBLE-PLAYBOOK-E PKNAME=HTTPD Var.yml example is assigned in playbook and called [[email protected] ansible]# vim var2.yml
    • Hosts:cen7
      Remote_user:root
      VARs://If you want to use the first variable in play VARs

      • username:user123//variable Name: assignment /li>
      • groupname:group123

      Tasks:

      • name:create group
        group:name={{GroupName}} Call variable
      • name:create uesr
        user:name={{username}} group={{groupname}} home=/app/{{username}}dir//can write change Volume plus other fields
        [[email protected] ansible]# ansible-playbook var2.yml
        [[email protected] ansible]# ansible Cen7-a ' getent passwd user123 '
        192.168.27.101 | SUCCESS | Rc=0 >>
        User123:x:1001:1001::/app/user123dir:/bin/bash Example 2: variable

        Vim var2.yml
        -hosts:websrvs
        Remote _user:root
        VARs:

        • username:user1
      • groupname:group1

      Tas KS:

      • name:create Group
      • group:name={{GroupName}} state=present
      • name:create US ER
        user:name={{Username}} state=present

Ansible-playbook var2.yml ansible-playbook-e "Username=user2 groupname=group2" var2.yml

Multiple packages can be installed or uninstalled at once using the Yum module

Ansible cen7-m yum-a ' name=dstat,httpd state=absent '

The playbook of 3.3 ansible

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.