Host list for ansible, yml syntax, playbook details + operations

Contents of this chapter:
inventory host list
2. yml grammar
3. playbook Details + Operations

inventory host list

ansible The default host list is/etc/ansible/hosts file
//Host lists can be set manually or generated dynamically through Dynamic Inventory
//Use FQDN for generic hostname

vi /etc/ansible/hosts
[webserver]      #Square bracket set group name
www1.example.org    #Define the monitored host, which can be either a hostname or an IP address. The hostname needs to be modified in the / etc/hosts file
www2.example.org:2222     #Define remote connection port after colon, default is port 22 of ssh

//If you have hosts with similar names, you can use a list to identify each host
[webserver]
www[01:50].example.org ansible_ssh_user=root ansible_ssh_pass=123456

[dbbservers]
db-[a:f].example.org

Here are the variables in Inventory

(1)Host variable
[webserver]
www1.magedu.com http_port=80 maxRequestsChild=808
www2.magedu.com http_port=8080 maxRequestsChild=909
(2)Group variable
[servers:vars]
ntp_server=ntp.example.org
nfs_server=nfs.example.org
(3)group nesting
[apache]
http1.example.org
http2.example.org

[nginx]
ngx1.example.org
ngx2.example.org

[webservers:children]
apache
nginx

(4)inventory Variable parameters
//Parameter Description
ansible_ssh_host    Remote host name to connect to.Unlike the alias of the host you want to set,Set with this variable.
ansible_ssh_port    ssh Port number.If not the default port number,Set with this variable.
ansible_ssh_user    Default ssh User name
ansible_ssh_pass    ssh Password(This is not safe,We strongly recommend using --ask-pass or SSH secret key)
ansible_ssh_private_key_file    ssh Private key file used.For multiple keys,And you don't want to use it SSH Agent situation.
ansible_ssh_common_args This setting is attached to sftp,scp and ssh Default command line
ansible_sftp_extra_args This setting is attached to the default sftp Command line.
ansible_scp_extra_args  This setting is attached to the default scp Command line.
ansible_ssh_extra_args  This setting is attached to the default ssh Command line.
ansible_ssh_pipelining  Determine whether to use SSH The Conduit.This can cover ansible.cfg Medium settings.
ansible_shell_type  Target System shell type.By default,Execution Use of Commands 'sh' grammar,Can be set to 'csh' or 'fish'.
ansible_python_interpreter  Target Host's python Route.Where applicable: There are multiple in the system Python, Or the command path is not"/usr/bin/python",such as *BSD, perhaps /usr/bin/python
ansible_*_interpreter   There"*"Can be ruby or perl Interpreters in other languages, roles, and functions ansible_python_interpreter Similar
ansible_shell_executable    This will set ansible The controller will be used on the target machine shell,cover ansible.cfg Configuration in, defaults to/bin/sh. 

yaml syntax

The difference between an object and a collection:

object
  Attribute 1 length: 5m
  Attribute 2 Width: 2m
  Attribute 3 High: 1.5m
 aggregate
  Object 1
  Object 2
  Object 3

YAML: Another markup language.Is the language used to write the configuration file, very simple and powerful.
YAML syntax is similar to other languages in that it can also express data structures such as hashes, scalars, and so on.
The structure is represented by spaces; the configuration items in the sequence are represented by -; the key values in Map are separated by: and the extension of YAML is yaml

Basic grammar rules:

1. Case Sensitive
 2. Use indentation to represent hierarchical relationships
 3. Tab keys are not allowed for indentation, only spaces are allowed.
4. The number of indented spaces is not important, as long as the elements of the same level are aligned to the left

Data structures supported by YAML:
1. Object: A set of key-value pairs, also known as mapping/hashes/dictionary
 For example: name:Example Developer
        Key Value
 2. Array: A set of ordered values, also known as a sequence/list
 For example: -Apple
       -Orange
 3. Pure quantity: a single, non-divisible value
 For example: number:12.30
       sure: true

yaml example:

name:zhangsan
age:20
name:lisi
age:22
people: 
-name:zhangsan
      age:20
      -name:lisi
      age:22

playbook detail + operation

Ansible's script--playbook

Call ansible's template through task to organize multiple plays into one playbook.
playbooks itself consists of the following components
(1) Tasks: Task is an operation that calls a module to complete; equivalent to a transaction, it is rolled back without success
(2) Variables: variable, host list, script, command-e declaration variable, three scenarios
(3) Templates: Templates
(4) Handlers: Processors that trigger actions when a condition is met;
(5) Roles: Roles.

Here is an example of a playbook

- hosts: webserver              //Defined host group, that is, the applied host
  vars:                        //Define Variables
    http_port: 80
    max_clients: 200
  user: root
  tasks:                               //Tasks performed
  - name: ensure apache is at the latest version #Friendly tips, self-defined
    yum: pkg=httpd state=latest #Check if the httpd package is up to date
  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf
    notify: #The call triggers the following specific action
    - restart apache
  - name: ensure apache is running
    service: name=httpd state=started
  handlers:                       //processor
    - name: restart apache #Adjust this action
      service: name=httpd state=restarted

//Execute a playbook
ansible-playbook [yaml file name]
//For example: ansible-playbook ping.yml
//Parameter: -k(-ask-pass) is used to enter ssh password interactively
      -K(-ask-become-pass) Used for interactive input sudo Password
      -u   Specify User
//Supplementary commands:
ansible-playbook nginx.yml --syntax-check    #Check that the syntax of the yaml file is correct
ansible-playbook nginx.yml --list-task       #Check tasks task
ansible-playbook nginx.yml --list-hosts      #Check valid hosts
ansible-playbook nginx.yml --start-at-task='Copy Nginx.conf'     #Specify to run from a task

Experimental environment

Master
Controlled End 01 192.168.136.168
Controlled end 02 192.168.136.185
Controlled end 03 192.168.136.253

ansibel environment deployment, join host list

[webserver]
192.168.136.168
[mysql]
192.168.136.185
[ftpserver]
192.168.136.253
#Turn off all host firewalls
[root@localhost ~]# systemctl stop firewalld.service 
[root@localhost ~]# setenforce 0
#Delivery Free
ssh-keygen -t rsa #Generate key, return, enter password
#Push Public Key to Other Host
ssh-copy-id root@192.168.136.168
ssh-copy-id root@192.168.136.185    //Configure key pair validation
ssh-copy-id root@192.168.136.253
root@localhost ~]# ssh-agent bash #ssh proxy
[root@localhost ~]# ssh-add #Add Password

Introduction to hosts and users

[root@localhost ~]# vim a.yml

- hosts: webserver               #Specify a host group, which can be one or more groups.
  remote_user: root                #Specify user name for remote host execution

[root@localhost ~]# ansible-playbook a.yml 

PLAY [webserver] ***************************************************************

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

PLAY RECAP *********************************************************************
192.168.136.168            : ok=1    changed=0    unreachable=0    failed=0   

You can also define a remote execution user for each task:

---
- hosts: mysql
  remote_user: root             
  tasks:
    - name: test connect
      ping:
      remote_user: root          #Specify that the remote host executes tasks with the running user mysql
//When playbook is executed: ansible-playbook ping.yml
LAY [webserver] *******************************************************************

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

TASK [test connect] ****************************************************************
ok: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=0    unreachable=0    failed=0   

Specify remote host sudo switching user:

---
- hosts: mysql
  remote_user: root            
  become: yes                  #Parameter after version 2.6, previously sudo, meaning to switch user runs
  become_user: mysql          #Specify sudo user as mysql
//When playbook is executed: ansible-playbook ping.yml-K

tasks Lists and action
1.Play The main part is task List, task Tasks in the list are listed one by one in the hosts Execute on the host specified in, that is, start the second task after completing the first task on all hosts.
//When running playbook (top-down), if a host fails to execute the task, the entire task will roll back. Correct the error in playbook and execute it again.
Task The purpose is to execute the module using the specified parameters, whereas variables can be used in the module parameters, which are idempotent when the module executes, meaning that multiple executions are safe because the results are consistent.
2.Every last task Must have a name name,This works playbook When a task is executed, its output tells you which one it belongs to. task Of.If not defined name,'action'The value of will be used as a token-specific in the output information task. 
3.Define a task,Common formats:"module: options" For example: yum: name=httpd
4.ansible In its own module, command Modules and shell Modules do not need to be used key=value format

//A small example:
---
- hosts: webserver
  remote_user: root
  tasks:
   - name: disable selinux
     command: '/sbin/setenforce 0'
   - name: install httpd
     yum: name=httpd  

 #This side can also close the firewall with a section:
   - name: disable firewalld
     service: name=firewalld state=stopped

   - name: start httpd
     service: name=httpd state=started
[root@localhost ~]# ansible-playbook a.yml 

PLAY [webserver] *******************************************************************

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

TASK [disable selinux] *************************************************************
changed: [192.168.136.168]

TASK [install httpd] ***************************************************************
changed: [192.168.136.168]

TASK [start httpd] *****************************************************************
changed: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=4    changed=3    unreachable=0    failed=0   

play As long as the return value of the execution command is not zero, an error will be reported. tasks Stop it

//Modify as follows: Join execution failure, we can set a parameter to skip a problem and continue with ignore_errors: True 
---
- hosts: webserver
  remote_user: root
  tasks:
   - name: disable selinux
     command: '/sbin/setenforce 0'
     ignore_errors: True             #Ignore errors and force return to success
   - name: make sure apache is running
     service: name=httpd state=started

Here is another example to read

---
- hosts: webserver
  remote_user: root
  tasks:
   - name: create nginx group
     group: name=nginx system=yes gid=208
   - name: create nginx user
     user: name=nginx uid=208 group=nginx system=yes
- hosts: mysql
  remote_user: root
  tasks:
   - name: copy file to mysql
     copy: src=/etc/inittab dest=/opt/inittab.back

Introduction to Handlers

Handlers are also lists of some tasks and are no different from normal tasks.
Notify by the notifier, Handlers will not execute if it is not notified, Handlers will execute if it is notify
 No matter how many notifies there are, handlers will only be executed once until all the task s in the play have been executed

Example
---
- hosts: webserver
  remote_user: root
  tasks:
   - name: install httpd package
     yum: name=httpd state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf
     notify:
      -restart httpd
   - name: start httpd service
     service: enabled=true name=httpd state=started
  handlers:
   - name: restart httpd
     service: name=httpd state=restarted

Variables can also be introduced
    ---
- hosts: webserver
  remote_user: root
  vars:
  - package: httpd
  - service: httpd
  tasks:
   - name: install httpd package
     yum: name={{package}} state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf
     notify:
      -restart httpd
   - name: start httpd service
     service: enabled=true name={{service}} state=started
  handlers:
   - name: restart httpd
     service: name={{service}} state=restarted

#Write a small column of introduced variables that create users
[root@localhost ~]# vim b.yml 
- hosts: ftpserver
  remote_user: root
  vars:
   - username: lisi
  tasks:
   - name: create user
     user: name={{username}}
[root@localhost ~]# ansible-playbook b.yml --syntax-check

playbook: b.yml
[root@localhost ~]# ansible-playbook b.yml 

PLAY [ftpserver] *******************************************************************

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

TASK [create user] *****************************************************************
ok: [192.168.136.253]

PLAY RECAP *************************************************************************
192.168.136.253            : ok=2    changed=0    unreachable=0    failed=0   
ansible-playbook b.yml -e username=lisi
 Host lists can also add users to use

playbook uses variable methods:
1. Pass through the ansible command
 For example, edit the following yaml
vi a.yml
---
- hosts: mysql
  remote_user: root
  vars:
  - user:
  tasks:
  - name: add new user
    user: name={{user}}
Then execute the command: ansible-playbook a.yml-e "user=testvar"
Can execute commands to view: ansible mysql-m command-a'tail/etc/passwd'

2. Define variables directly in yaml--as in the handlers example above
 3. Direct reference to some variables
 For example, reference to a fixed variable in ansible
 #content Specifies the file contents to the path
vi test.yml
---
- hosts: mysql
  remote_user: root
  tasks:
   - name: copy file
     copy: content="{{ansible_all_ipv4_addresses}}," dest=/opt/vars.txt
 Execute command: ansible-playbook test.yml
 Go to 253 to view the contents of vars.txt file
[root@localhost opt]# cat add.txt 
["192.168.122.1", "192.168.136.253"]

Another example is: referencing host variables
vi /etc/ansible/hosts
 Add the following after the host in the mysql group
[mysql]
192.168.80.183 testvar="80.183"#Define the value of the testvar variable to 80.183
 vi test.yml #Add {{testvar}} host variable
---
- hosts: mysql
  remote_user: root
  tasks:
   - name: copy file
     copy: content="{{ansible_all_ipv4_addresses}},{{testvar}}" dest=/opt/vars.txt
 Execute command: ansible-playbook test.yml
 Go to 183 to see the contents of the vars.txt file

---------------------------------------

If you need to depend on a variable, facts(setup)Or as a result of a previous task task Conditional tests are used when executing a prerequisite or not. Playbook Medium Conditional Test Usage when Clause.
//A conditional test can be used by adding a when clause after a task: the when clause supports a jinjia2 expression or syntax, for example:
vi when.yml
---
- hosts: mysql
  remote_user: root
  tasks:
    - name: "shutdown CentOS"
      command: /sbin/shutdown -h now #-r Restart
      when: ansible_distribution == "CentOS"
PLAY [mysql] ***********************************************************************

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

TASK [shutdown CentOS] *************************************************************
fatal: [192.168.136.185]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Shared connection to 192.168.136.185 closed.\r\n", "unreachable": true}
    to retry, use: --limit @/root/b.retry

PLAY RECAP *************************************************************************
192.168.136.185            : ok=1    changed=0    unreachable=1    failed=0   

Multi-condition Judgment

vi when.yml
---
- hosts: mysql
  remote_user: root
  tasks:
    - name: "shut down CentOS 6 systems"
      command: /sbin/shutdown -r now
      when:
        - ansible_distribution == "CentOS"
        - ansible_distribution_major_version == "6"

Group condition judgment (and, and, or)

vi when.yml
---
- hosts: mysql
  remote_user: root
  tasks:
    - name: "shut down CentOS 6 and Debian 7 systems"
      command: /sbin/shutdown -t now
      when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6") or
            (ansible_distribution == "Debian" and ansible_distribution_major_version == "7")

Custom variables for conditional testing

#Create files when true, delete old False
vi when.yml
---
- hosts: all
  vars:
    exist: "True"
  tasks:
  - name: creaet file
    command:  touch /tmp/test.txt
    when: exist | match("True") #Match:match

  - name: delete file
    command:  rm -rf /tmp/test.txt
    when: exist | match("False")    

TASK [Gathering Facts] *************************************************************
ok: [192.168.136.253]
ok: [192.168.136.168]
ok: [192.168.136.185]

TASK [creaet file] *****************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.136.185]
changed: [192.168.136.253]
changed: [192.168.136.168]

TASK [delete file] *****************************************************************
skipping: [192.168.136.253]
skipping: [192.168.136.168]
skipping: [192.168.136.185]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.185            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.253            : ok=2    changed=1    unreachable=0    failed=0   

---------------------------#is equivalent to traversal

Iteration mechanisms can be used when there are tasks that require repetitive execution.It is used in a format that defines what will need to be iterated as item Variable references, and through with_items Statement specifies an iterated list of elements.For example:
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: "Install Packages"
      yum: name={{ item }} state=latest #item:Go through the following collection
      with_items: #Step by step installation
        - httpd
        - mysql-server
        - php   
//You can also define it yourself (you can also set the array as a whole line, followed by a property variable name).
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: "Add users"
      user: name={{ item.name }} state=present groups={{ item.groups }}
      with_items:
        - { name:'test1', groups:'wheel'}
        - { name:'test2', groups:'root'}

#Small Events
- hosts: all
  vars:
    exist: "False"
  tasks:
  - name: create users
    user: name={{item}}
    with_items:
     - t01
     - t02
     - t03

ok: [192.168.136.253]
ok: [192.168.136.168]
ok: [192.168.136.185]

TASK [create users] ****************************************************************
changed: [192.168.136.253] => (item=t01)
changed: [192.168.136.168] => (item=t01)
changed: [192.168.136.185] => (item=t01)
changed: [192.168.136.253] => (item=t02)
changed: [192.168.136.168] => (item=t02)
changed: [192.168.136.185] => (item=t02)
changed: [192.168.136.253] => (item=t03)
changed: [192.168.136.168] => (item=t03)
changed: [192.168.136.185] => (item=t03)

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.185            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.253            : ok=2    changed=1    unreachable=0    failed=0   
#Go to the host to see if there are any of these users
t01:x:1001:1001::/home/t01:/bin/bash
t02:x:1002:1002::/home/t02:/bin/bash
t03:x:1003:1003::/home/t03:/bin/bash

Templates module

#Copy 168 httpd profile over
[root@localhost ~]# vim /etc/ansible/hosts 
[root@localhost ~]# scp root@192.168.136.168:/etc/httpd/conf/httpd.conf ./
httpd.conf                                        100%   11KB   4.0MB/s   00:00  
#Modify httpd configuration file
Listen {{http_port}} #variable
ServerName {{server_name}}
MaxClients {{access_num}}

mv httpd.conf httpd.conf.j2

#assignment
[root@localhost ~]# vim /etc/ansible/hosts 
[webserver]
192.168.136.168 http_port=192.168.136.168:80  server_name="www.yun.com:80" access_num=200 #Specify port, domain name, number of visits 200

[root@localhost ~]# vim apache.yml
- hosts: webserver
  remote_user: root
  vars:
   - package: httpd
   - service: httpd
  tasks:
    - name: check latest
      yum: name-{{package}} state=latest
    - name: configure apache
      template: src=/etc/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf #Source on local control side, specify opposite party's controlled side
      notify:
        - restart httpd
    - name: start httpd
      service: name={{server}} enabled=true state=started
  handlers:
    - name: restart httpd
      service: name={{server}} state=restarted

[root@localhost ~]# ansible-playbook apache.yml --syntax-check

playbook: apache.yml
[root@localhost ~]# ansible-playbook apache.yml 

PLAY [webserver] *******************************************************************

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

TASK [check latest] ****************************************************************
ok: [192.168.136.168]

TASK [configure apache] ************************************************************
changed: [192.168.136.168]

TASK [start httpd] *****************************************************************
changed: [192.168.136.168]

RUNNING HANDLER [restart httpd] ****************************************************
changed: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=5    changed=3    unreachable=0    failed=0   
#With this template, you can modify the configuration files of all hosts on the other controlled side uniformly.

//Go to two remote hosts to view
grep -i listen /etc/httpd/conf/httpd.conf
grep -i maxClient /etc/httpd/conf/httpd.conf
grep -i servername /etc/httpd/conf/httpd.conf

tags module

In a playbook, we usually define many task s. If we only want to execute one or more of them, we can use the tags tag function. The format is as follows:
vi hosts.yml
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: Copy hosts file
      copy: src=/etc/hosts dest=/etc/hosts
      tags:
      - only #Mark I only do what I mark
    - name: touch file
      file: path=/opt/hosts state=touch
 Execute command: ansible-playbook hosts.yml --tags="only"
PLAY [webserver] *******************************************************************

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

TASK [Copy hosts file] *************************************************************
ok: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=0    unreachable=0    failed=0   

ansible-playbook hosts.yml

In fact, you can specify more than one tags for a single or multiple task.playbook also provides a special tags for always.The purpose is that when using always when tags are tasked, tags with always defined will execute regardless of which tags are executed.
vi hosts.yml
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: Copy hosts file
      copy: src=/etc/hosts dest=/etc/hosts
      tags:
      - only
    - name: touch file
      file: path=/opt/hosts state=touch
      tags:
      - always
 Execute command: ansible-playbook hosts.yml --tags="only"
Go to two managed servers to view file creation

Tags: ansible MySQL ssh Apache

Posted on Sun, 09 Feb 2020 09:28:59 -0800 by cybercrypt13