ansible entry, use ansible-playbook, through the script batch management (two)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/ck784101777/article/details/102619042

[Ansible Getting a] https://blog.csdn.net/ck784101777/article/details/102593155

A, ansible seven weapons

1. The first weapon ansible

ansible command for performing temporary work, you must master

2. The second weapon ansible-doc

ansible-doc is documented ansible module for each module has a detailed description and application case reports, a similar function and Linux man command

3. The third weapon ansible-console

ansible-console is to provide users with interactive tools ansible, the user can then ansible-console on virtual terminal out of the same like with Sheel use ansible built-in command. This is done using an interactive shell is used to provide a user experience

4. The fourth weapon ansbile-galaxy

ansbile-galaxy from github download manager Roles of a tool, similar to the python pip

5. The fifth weapon ansible-playbook

ansible-playbook everyday applications most frequently used commands, working mechanism is by reading good writing playbook for batch file management first, it can be understood as ansible task set by the composition of certain conditions

6. The sixth weapon ansible-valut

ansible-valut mainly used to configure file encryption, such as the playbook written file contains sensitive information and can not make people see, by ansible-vault file encryption times

7. 7 kinds of weapons ansbile-pull / push

ansbile-pull, ansible has two operating modes pull / push, push default mode operation, pull and push mechanisms operating mode opposite .push will be pushed to the remote command, pull the load command from the remote

Applicable to high-volume machine needs to be configured, even with high concurrent threads still need to spend a lot of time, their efficiency is almost unlimited upgrade, operation and maintenance personnel skill level and forward planning have higher requirements

This chapter focuses on the use of the ansible-playbook

 

二、ansible-playbook

Learn anisble-playbook divided into the following steps:

Learn what playbook is -> syntax to understand the playbook (understand yaml, playbook written by yaml Language) -> Learn grammar constitute the play of the playbook -> able to read the results of the playbook (understand JSON, display the results output to JSON)

 

What is 1.playbook

 ansbile playbook is used to configure, deploy and manage hosted script host, the detailed description of the playbook, perform a series of tasks which allows remote hosts to achieve the desired state, that is, playbook alphabet letter That means the script, reality according to the script performances by the actors in the ansible by the computer installation, deployment, application mentioned external services, computer processing and organizing all sorts of things

 

2. Why playbook

 Conventional batch processing operation of the machine is to write a script to loop through remote execution operation ssh, in a conventional manner with the client script first, coupling high, if the managed machine ip change also modify the script. The playbook can be used repeatedly write good code, and only on the manager. playbook like a function, most of the operations maximize the use of the code, using the ansible process, the process is not write playbook

 And anible provides a large number of modules can be used in the playbook

 

3.playbook of syntax

-playbook written by YAML language, follow the standard YAML

- In the same line, after the contents # denotes a comment

- with a list of elements should remain the same indentation

-playbook composed of one or more play

-play comprising hosts, variables, roles, tasks and other objects, which represents the key intermediate in the method are: that the partition ""

-YAML there is a small quirk, it's the beginning of the file must be written ---, which is part of the YAML format, indicating the beginning of a file, like a shell of #! / Bin / bash

 

3.5YAML language (supplement)

YAML basic grammar:

-YAML structure through space to show

- an array using the '-' indicates

- key-value pair by a ':' represents

- use indention data hierarchy relationship

- Generally speaking, each composed of two or more of spaces to indent (non-essential, but do not use the tab, and ensure that at least one space indentation)

- # denotes a comment

example:

Key-value pair:  "name": "Flow of China"

Or "name":

    "Flow of China"

Array: "Name":

       - "Flow of China"

       - "pot into rich"

       - "Chapter study tours"

These three values ​​are subordinate to 'name' is key

 

4.play composition

-hosts: To perform a remote host definition of group playbook

-remote_user: define what the user executes a command (typically root)

-vars: run-time variables need to use the definition playbook

-tasks: define the list of tasks to be executed on the remote host

-handlers: definition of task execution is completed need to call the task

 

5.playbook execution results

- Use ansible-playbook playbook run file, the contents of the output JSON format, composed of different colors for easy identification

- successfully execute on behalf of green

- Yellow is executed successfully, generally showing a yellow after the documents have been altered, and the display change: ture

- red for failed

- *** represents the system state changes

5.5.JSON (supplement)

-Json is JavaScript Object Notation, which is a text based on the light data interchange format and language independence

-JSON delimiter limited to a single quote " '" parentheses "()" brackets "[]" braces "{}", colon ":" and a comma ","

-JSON plain text language, comprising self-descriptive (human readable) and hierarchy (support median value), does not have the logical (no logic programming statements) may be analyzed by the JavaScript

 

format:

Key-value pairs: { "name": "Hua stream"}

Array: { "name": [ "China Flow" and "Chapter learn oil"]}

Array (median value, nesting): { "Name": [{ "Chinese stream": "Long handsome", "Age": 20}

                    { "Chapter to learn oil": "sing good", "age": 21}

                   ]  

              }

rule:

- whether single or an array of key-value pairs, must be added to "{}"

- An array to determine a key name, the value must use the "[]" to expand up

- the value pattern array support value, i.e., defines a key, which key can still create key-value pairs, each pair of key-value pairs with requirements "{}" spread from

- Digital type does not require double quotes Expanding expansion up

 

Three, ansible-play case

Write a ansible-play script requires the following steps:

Defined group -> Create and write the playbook script -> Script execution

 

Next, I'll cited several examples, in each case you will see some specific modules and use play action

 

1. Case 1- Bulk create user

Requirements: Add User zhangsan to all hosts, set a password 123

1) Create a group

On the one I told aansible order to find the configuration file and distribute machine management certificate file, can not read, please review the previous article (beginning connection)         

  1. [root@ansible ansible] cd /etc/ansible
  2. [root@ansible ansible] mkdir myansible
  3. [root@ansible ansible] vim myhosts
  4. [web]
  5. web1
  6. web2
  7. [All: vars]
  8. ansible_ssh_private_key_file="/root/.ssh/id_rsa"

2) writing the script playbook

.yml yaml file format must be strictly observed, the festival has to say. Comply with the rules hierarchy, the same alignment layer, sub-layer to ensure indented at least one space, "-" and: a space after the fight before you can write the value ""

Format script execution playbook: ansible-playbook * .yml

There is a detail that password parameters user module, is not read? Read on the right, create a password conventional command should be: echo 123 | passwd --stdin zhangsan (I can execute this command with a shell module), and here I use a variable filter, in fact if you conventional manner, ansible the shell module will direct write Shadow password, and the password is not placeholders, since the user needs to log in after the collation password encryption, but this time to check for the password is not encrypted, then the problem comes, it certainly is not on, so you can not log in

as follows:

So you need to use a variable filter (Linux using sha512 encryption):

password_hash

Format {{ 'urpassword' | password_hash ( 'sha512')}}

  1. [root@ansible ansible] vim createUsers.yml
  2. ---
    - hosts: web
      remote_user: root
      tasks:
        - user:
            name: zhangsan
            password: "{{'123456' | password_hash('sha512')}}"  
  3. [root@ansible ansible]# ansible-playbook createUsers.yml          
  4. PLAY [web] ******************************************************************
  5. TASK [Gathering Facts] ********************************************************
  6. ok: [web]
  7. TASK [create user zhangsan] ***********************************************
  8. changed: [web]
  9. TASK [command] ****************************************************************
  10. changed: [web]
  11. PLAY RECAP ********************************************************************
  12. cache : ok=4 changed=2 unreachable=0 failed=0

 

2. Case 2- batch create advanced user, using variables

Case 1 Create a user has a limitation that a user can only create a script, the next time you want to create a different user can only modify the script, and user scripts coupling is relatively high, we can use variables to liberate this coupling. Here are four ways to use variables

First we have to modify the script, we adopted the "{{key}}" to use variables, double brackets put the key name

---
- hosts: web
  remote_user: root
  tasks:
    - user:
        name: "{{user}}"
        password: "{{'123456' | password_hash('sha512')}}"

1) Enter the variable (external)

Format: ansible-playbook * .yml -e "key = value"

ansible-playbook userCreate.yml -e "user=lisi"
 

 

2) json reference variable (external)

Start by creating a json file and write data in it

vim user.json

{"user":"zhangsan"} 

Format: ansible-playbook * .yml -e ". @ * Json" # quoted when to add an @ in front, do not ask why, the rules

ansible-playbook userCreate.yml -e "@user.json"

 

3) references yml variable (external)

Yml first create a file, write data inside

vim user.yml

---

user: zhangsan 

Format: ansible-playbook * .yml -e ". @ * Yml" # quoted when to add an @ in front, do not ask why, the rules

ansible-playbook userCreate.yml -e "@user.yml"

 

4) Use a script built-in variables (built-in)

 Use vars:

           Key: value

---
- hosts: web
  remote_user: root
  vars :
    user: zhaoqiang
  tasks:
    - user:
        name: "{{user}}"
        password: "{{'123456' | password_hash('sha512')}}"

 

3. Case 3- batch install Apache Service

Requirements: The playbook install Apache, modify the port configuration ServerName, modify the home page, set the boot from Kai

I do not define a set of reference Case 1

1) write the script playbook

Ansible on the use of modules described in my previous article, there are links to the beginning of the article

Here the main use yum module, lineinfile modules, copy modules and service modules

step:

1_ install apache

2_ modified apache port 8080 using module lineinfile

3_ Start Service

4_ index.html copied to the local machine each managed

5_ test

  1. [root@ansible ansible]# echo "hello world" > index.html
  2. [root@ansible ansible]# vim http.yml
  3. ---
  4. - hosts: cache
  5.   remote_user: root
  6.   tasks:
  7.      - name: install one specific version of Apache
  8.        yum:
  9.           name: httpd // install Apache
  10.           state: installed
  11.      - lineinfile:
  12.           path: /etc/httpd/conf/httpd.conf
  13.           regexp: '^Listen '
  14.           line: 'Listen 8080' // modify port 8080
  15.      - service:
  16.           name: httpd
  17.           enabled: yes // boot from Kai
  18.           state: restarted
  19.      - copy:
  20.           src: /root/index.html // modify the home page, you can write your own pages
  21.           : /var/www/html/index.html
  22. [root@ansible ansible]# ansible-playbook http.yml
  23. [root@ansible ansible]# curl 192.168.1.45:8080           //测试
  24. hello world

 

4. Case 4- ignore the error and continue execution of the script

 Conventional processing error during execution of ansible-playbook is to stop the execution of the script, but in many cases we do not want it to stop executing, for example, we create a file, if the file exists, then this time ansible-playbook will stop execution but we do not want to stop here to perform, because it will not affect the final result (if the file already exists, even if we do not execute the command will create the existence of this document, the result of the whole process is the same, which is idempotency program )

Script does not want to interrupt the execution of a very simple, only need to add a parameter to

ignoring_errors:True

We create a user and add it to a group that does not exist, there would be an error, we ignore the errors, you can see that ignore the error, the script will continue execution

---
- hosts: web
  remote_user: root
  tasks:
    - user:
        name: "{{user}}"

     group: abc
        password: "{{'123456' | password_hash('sha512')}}"

        ignoring_errors:True

...........

fatal: [web1]: FAILED! => {"changed": false, "msg": "Group iwq does not exist"}
...ignoring
 

For when to use ignoring_errors: True is the operator needs strengthening exercises, generally requires a forward-looking, know what will go wrong, and this error will not affect the final result fundamentally. Strengthening exercises it, sprouting new

 

5. Case 5, restart apache service, Trigger: configuration file is modified

 Case Description: We playbook when writing the script, and some part does not necessarily need to perform every time, we can give it to write a trigger condition, the implementation of this section that is triggered when a certain condition before. As we in the batch edit apache configuration file, the original port 80 to 8080, and some hosts already 8080, then we do not need to reboot the host of this service.

 This example will need notify this action, notify each can be triggered because the last play of, copy self-test function, it will compare your files with the target host file, as if the two are not replaced, if it is inconsistent replace, and gives prompt change. And notify will change as a trigger, select whether to perform. If the change, the next action handler is called display, handler will perform a good operation definition

The order of execution:

File content is changed?

- has not changed, do not violate action

- change, nofity is triggered, execution handle

The present embodiment uses the copy module can be used to modify lineinfile module row. If you use the copy you need to prepare the appropriate documents on the management host

  1. [root@ansible ansible]# vim handers.yml
  2. ---
  3. - hosts: web
  4.   remote_user: root
  5.   tasks:
  6.     - copy:
  7.         src: httpd.conf
  8.         : /etc/httpd/conf/httpd.conf
  9.         owner: apache
  10.         group: apache
  11.         mode: 0644
  12.       notify:
  13.         - restart httpd
  14.   handlers:
  15.     - name: restart httpd
  16.       service:
  17.           name: httpd
  18.           state: restarted

The first performance, trigger action

The second execution, the action does not violate

 

6. Case 6, the system load is too high the Apache service stops

Case Description : Use the uptime command to view real-time load, when the load is greater than one minute 0.7 web server stopped

 uptime # 1 minute load, respectively, 5 minutes, 10 minutes
 15:22:02 up 3:38, 1 user, load average: 0.48, 0.16, 0.09

本例要学习几个陌生的模块

register模块用来保存前一个命令的返回状态,可以在之后进行调用

格式:register: 键名

调用: 键名.stdout   (stdout标准化输出)

when模块用于在满足指定条件后触发一项操作

格式: when 条件

  1. [root@ansible ansible]# vim when.yml
  2. ---
  3. - hosts: web
  4.   remote_user: root
  5.   tasks:
  6.     - shell: uptime | awk '{printf("%.2f\n",$(NF-2))}'                  #NF从后面数,$.2f 占位符
  7.       register: result
  8.     - service:
  9.         name: httpd
  10.         state: stopped
  11.       when: result.stdout|float > 0.7          

#|float将标准化输出作为浮点数,因为register默认保存的是字符串,而字符串不能比较大小

使用awk 'BEGIN{while(1){}}'制造死循环增加负载

可以用watch -n 1 'uptime' 实时监控uptime的负载

7.案例7,一次性创建多个用户

本例需要用到with_items模块,用过item调用变量值

  1. ---
  2. - hosts: web
  3.   remote_user: root
  4.   tasks:
  5.     - user:
  6.         name: "{{item}}"
  7.         password: "{{'123456' | password_hash('sha512')}}"
  8.       with_items: ["wyf1","wyf2","wyf3","wyf4"]
     

进阶用法:with_items数组 

引用方式item.键名

  1. ---   
    - hosts: web2
      remote_user: root
      tasks:
        - name: add users
          user: 
            name: {{item.name}}
            group: {{item.group}}  
            password: {{'123456' | password_hash('sha512')}}
          with_items:
            - {name: 'nb',  group: 'root'}
            - {name: 'dd',  group: 'root'}
            - {name: 'plj', group: 'wheel'}
            - {name: 'lx',  group: 'wheel'                    

8.案例8,组合playbook

  在编写playbook的时候随着项目越来越大,playbook越来越复杂。可以把一些play、task 或 handler放到其他文件中,通过包含进来是一个不错的选择

本例需要学习include模块,它可以引入一个项目的文件和目录

格式: include: 文件路径

  1. ...
  2. tasks:
  3. - include: tasks/users.yml               #导入变量,可以通过{{ user }}来使用这些变量
  4. - include: tasks/useradd.yml                      #导入添加用户模块
  5. handlers:
  6. - include: handlers/handlers.yml    #导入handles条件触发的执行模块

9. 

Guess you like

Origin blog.csdn.net/ck784101777/article/details/102619042