Ansibile the playbook acquaintance

  A, playbook Profile

  ansiblie task configuration file is called playbook, known as "script", each script (playbook) are included in a series of tasks, each task in the ansible which is also known as the "drama" (play), a play It contains extra drama. .

  Previously we have learned about ansible perform two ways to perform ad-hoc and ansible-playbook, ad-hoc mainly used for temporary orders, and playbook we can be understood as a collection of ad-hoc, somewhat similar to a shell script, ad-hoc on the equivalent of a shell script in the task bar statement, playbook is equivalent to the entire shell script. playbook is a list of one or more "play" composition, play a major function is to host a set of pre-defined, pre-defined roles dressed by ansible the task. The actual task is a module calls ansible will play multiple organizations in a playbook, that allows them to join together to perform a predefined action mechanism by prior arrangement.

 As illustrated above, the user can put a plurality of tasks (ad-hoc task) playbook written, the user invokes a command ansible-playbook choreographed playbook, ansible reads every play and the Task playbook, and in accordance with in order from top to bottom playbook sequentially performed, ansible each task calls the module defined to sequentially perform the corresponding task, and to the host in the list matches the corresponding host using the specified host playbook, then ssh authentication, the compiled transmits the corresponding file to perform tasks on a corresponding host or network device, and returns execution state.

  Two, YAML Profile

  playbook using yaml language, yaml is a high readability of sequence data formats language used to express it very reference to the other languages, including: XML, C language, python, perl, etc. as well as e-mail format RFC2822. Clark Evans in 2001 and first published in this language, in addition Ingy döt Net and Oren Ben-Kiki is also the designer of this common language. YAML (YAML Is not Markup Language), a markup language that is not yaml. However, in the development of the language, yaml means in fact: "Yet Another Markup Language" (still a markup language)

  ymal properties

  1) Good readability YAML

  2) interaction and scripting languages ​​YAML good

  3) YAML data types that implement languages

  4) YAML has a consistent message template

  5) YAML easy to implement, based on the processing flow, strong communication skills and good scalability

More information and specifications please refer to the official documentation http://www.yaml.org

  Three, playbook grammar Introduction

  1) the need to "---" (three minus sign) to start, and the need to write the top of the line. Another optional number three consecutive points (...) is used to indicate the end of the file.

  2) times the normal line to start writing content playbook, the proposed trip to write the playbook of features, of course, do not write also possible.

  3) Use the "#" commented code.

  4) indentation must be unified, not spaces tab mix.

  5) the level of indentation must be consistent, the same indentation on behalf of the same level, the program determines whether any level of indentation is by wrapping to achieve binding.

  6) YAML file content and Linux sensitive mode has been determined, case sensitive (case sensitive), the value of k / v are case sensitive.

  7) the value of k / v counterparts may also write the write wrap. Peer use the ":" separator, wrap need to write "-" to separate.

  8) v can be a string, a list may be separately, of course, also be a dictionary.

  9) a complete block of code needs to have a minimum feature name: xxx (description of the task).

  10) include a name only a task

  11) yaml file extension is usually yml or yaml

list: list all of its elements are using - starting with ""

Example:

---
# A list of tasty fruits

- apple
- orange
- strawberry
- mango
~           

dictionary: dictionary, generally composed of a plurality of key and value

Example:

---
#An employee record
name: example developer
job: developer
skill: elite  

Of course, also possible key: value placed in {} represents performed by "," separated by a plurality of key: value

Example:

---
#An employee record
{name: example developer,job: developer, skill: elite}
~                                                         

  YAML syntax and other similar high-level language and can express simple lists, hash tables, scalar and other data structures. The structure (Structure) to show through space, the sequence (Sequence) in the entry with the "-" to represent, Map in the key-value pairs with the ":" separator.

Example:

---
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
~                    

  Four, playbook core elements

  1) hosts: list of remote hosts designated to perform the task (host group or individual hosts defined in the host list, support in front of said host pattern matching)

  2) tasks: task set

  3) varniables: built-in variable or a custom variable call playbook in

  4) templates: a template can replace the template file variable and perform some simple logic file

  5) handlers and notity combination, the operation starting from a specific condition, the condition just performed, or not performed

  6) tags Tags: to label specified task, we can perform according to the selection of the code label selectivity in the implementation of the playbook, as ansible-playbook -t tagsname useradd.yml, this means that the command useradd. yml were selected tag named tagsname task execution

   Five, playbook basic components

  1)hosts:

    The purpose of every play in the playbook is to allow the host to perform a specific task to a specified user. hosts for the specified host to perform tasks shall be defined in advance in the host list. hosts specified host as defined in the form of the same support as the host inventory, support wildcard, pattern matching and non-supporting host supports the IP address in addition to its mixing with the non-match.

Example: In websers group, but no longer dbsers group, hosts can be defined

---
- hosts: websers:!dbsers

  2) remote_user: task and the host can be used, which can also specify the manner by sudo remote tasks, which can be used to play a global or a task; Further, even when the handover designated by sudo_user sudo can be used when sudo user, as shown below

---
- hosts: websers:!dbsers
  remote_user: root

  tasks:
    - name: test connection
      ping:
      remote_user: qiuhom
      sudo: yes
      sudo_user: qiuping

  Note: The default sudo as root, meaning the cases specified sudo_user to qiuping, these tasks with sudo -u qiuping ping xxxx (on behalf of a host) command the same, of course, when using sudo We also need to authorize qiuhom on the target host, let qiuhom the user has permission to perform on behalf of qiuping the ping command.

  3) task list and action: play the main part of task list, each task in the task list one by one in sequence performed on all hosts specified in the hosts, i.e. after the completion of the first task on all hosts, and then start the second task; purpose task is to use the parameters specified execution module, the module parameters and variables can be used when the module performs idempotent, meaning that multiple times when safe, which means that the results are consistent; each task are should have its name, for outputting the execution result playbook recommended contents of tasks can be clearly described step, such as to provide a name, then the action will result for output.

  tasks: task list, it has the following two formats

    (1)action: module arguments

    (2) module: arguments ## recommended

   Note: with the back shell is a command module and command module, rather than key = value

If a task in the running state is changed, by "notify" to notify the appropriate handlers; course task by "tags" tagging can be specified on a call using -t ansible-playbook command.

Example:

[qiuhom@test ~]$cat test.yml 
---
- hosts: websers:!dbsers
  remote_user: root

  tasks:
    - name: test connection
      ping:
      remote_user: qiuhom
      sudo: yes
      sudo_user: qiuping 
      tags: test
    - name: test command
      shell: /bin/ls /home/qiuhom/
[qiuhom@test ~]$ansible-playbook -t test test.yml 

  Description: Specifies the label name with -t, represents only run the task expression is located.

If a launch command or script code is not zero, it can be used as follows ignored or not to continue the following code

---
- hosts: websers:!dbsers
  remote_user: root

  tasks:
    - name: run this command and ignore the result
      shell: /usr/sbin/ip addr show eth0 || /bin/true
    - name: run this command and ignore the result
      shell: /usr/sbin/ip addr show eth0
      ignore_errors: True

  Description: Both approaches can be skipped without interrupting PlayBook command error, proceed with the following code, using the short-circuit or the former properties, which uses parameters to control ignore_errors

  Six, playbook run way

ansible-playbook <filename.yml> ... [options]

Common options:

  -C, --check: check only the changes may occur, but do not actually perform the operation, while the equivalent non-transport playbook, and whether the results of the same test had anticipated, but it's not really perform to the remote host. Common language test writing playbook grammar is wrong.

  --list-hosts: Host playbook to run the task list matched

  --list-tags: all tag names are listed playbook

  --list-tasks: List all the tasks names playbook

  --limit host list: the current playbook is performed only for a specified list of hosts hosts

  -v, -vv, -vvv: display during the execution of the playbook, -v, display relatively simple, -vv show more detail, -vvv show the entire process (in great detail)

[root@test ~]#cat test.yml 
---
- hosts: websers
  remote_user: root

  tasks:
    - name: run this command 
      shell: hostname
      tags: hostname
      ignore_errors: True
    - name: show ip addr
      shell: /sbin/ip addr show
      tags: showip
[root@test ~]#ansible-playbook test.yml --list-hosts

playbook: test.yml

  play #1 (websers): websers    TAGS: []
    pattern: [u'websers']
    hosts (2):
      192.168.0.128
      192.168.0.218
[root@test ~]#ansible-playbook test.yml --list-tags

playbook: test.yml

  play #1 (websers): websers    TAGS: []
      TASK TAGS: [hostname, showip]
[root@test ~]#ansible-playbook test.yml --list-tasks

playbook: test.yml

  play #1 (websers): websers    TAGS: []
    tasks:
      run this command  TAGS: [hostname]
      show ip addr      TAGS: [showip]
[root@test ~]#ansible-playbook test.yml --limit 192.168.0.218

PLAY [websers] ********************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.0.218]

TASK [run this command] ***********************************************************************************************
changed: [192.168.0.218]

TASK [show ip addr] ***************************************************************************************************
changed: [192.168.0.218]

PLAY RECAP ************************************************************************************************************
192.168.0.218              : ok=3    changed=2    unreachable=0    failed=0   

[root@test ~]#ansible-playbook test.yml --limit 192.168.0.218 -v
Using /etc/ansible/ansible.cfg as config file

PLAY [websers] ********************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.0.218]

TASK [run this command] ***********************************************************************************************
changed: [192.168.0.218] => {"changed": true, "cmd": "hostname", "delta": "0:00:00.002139", "end": "2019-11-16 23:11:02.996962", "rc": 0, "start": "2019-11-16 23:11:02.994823", "stderr": "", "stderr_lines": [], "stdout": "localhost.localdomain", "stdout_lines": ["localhost.localdomain"]}

TASK [show ip addr] ***************************************************************************************************
changed: [192.168.0.218] => {"changed": true, "cmd": "/sbin/ip addr show", "delta": "0:00:00.002604", "end": "2019-11-16 23:11:03.733004", "rc": 0, "start": "2019-11-16 23:11:03.730400", "stderr": "", "stderr_lines": [], "stdout": "1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN \n    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00\n    inet 127.0.0.1/8 scope host lo\n    inet6 ::1/128 scope host \n       valid_lft forever preferred_lft forever\n2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000\n    link/ether 00:0c:29:e8:f6:7b brd ff:ff:ff:ff:ff:ff\n    inet 192.168.0.218/24 brd 192.168.0.255 scope global eth0\n    inet6 fe80::20c:29ff:fee8:f67b/64 scope link \n       valid_lft forever preferred_lft forever\n3: pan0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN \n    link/ether d2:7a:38:cf:27:60 brd ff:ff:ff:ff:ff:ff", "stdout_lines": ["1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN ", "    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00", "    inet 127.0.0.1/8 scope host lo", "    inet6 ::1/128 scope host ", "       valid_lft forever preferred_lft forever", "2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000", "    link/ether 00:0c:29:e8:f6:7b brd ff:ff:ff:ff:ff:ff", "    inet 192.168.0.218/24 brd 192.168.0.255 scope global eth0", "    inet6 fe80::20c:29ff:fee8:f67b/64 scope link ", "       valid_lft forever preferred_lft forever", "3: pan0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN ", "    link/ether d2:7a:38:cf:27:60 brd ff:ff:ff:ff:ff:ff"]}

PLAY RECAP ************************************************************************************************************
192.168.0.218              : ok=3    changed=2    unreachable=0    failed=0   

[root@test ~]#

  Description: - limit specified by the host must be said that within the specified range of hosts in the playbook.

   七、playbook vs shell scripts

  1) shell script is as follows:

#! / bin / bash 
# install the Apache 
yum -y install httpd --quiet 
# copy the configuration file 
cp /tmp/httpd.conf /etc/httpd/conf/httpd.conf 
cp / tmp / vhosts.conf / etc / httpd / conf.d / 
# to start Apache, and set the boot 
Service httpd start 
chkconfig httpd ON

  2)playbook

---
- hosts: websers
  remote_user: root

  tasks:
    - name: create apache group
      group: name=apache gid=80 system=yes
    - name: create apache user
      user: name=apache uid=80 group=apache system=yes shell=/sbin/nologin home=/var/www/html 
    - name: install httpd
      yum: name=httpd
    - name: copy config file
      copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/
    - name: copy config 2 file
      copy: src=/tmp/vhosts.conf dest=/etc/httpd/conf.d/
    - name: start httpd service
      service: name=httpd state=started enabled=yes     

  Description: Both are the same purpose, the advantages are obvious advantages than the script playbook more, playbook tasks can be performed for many hosts, but the script can only be executed on a host computer; no power repeat the script equivalence, it is likely to bring a lot of mistakes, and the playbook does not have such distress.

Guess you like

Origin www.cnblogs.com/qiuhom-1874/p/11871741.html