Ansible script management (example explanation!!!)

Keywords: ansible vim MySQL Nginx

inventory host list

The default host list of ansible is the / etc/ansible/hosts file. The host list can be set manually or generated dynamically through Dynamic Inventory. Generally, the host name uses FQDN
vim /etc/ansible/hosts
[webserver]                          #Square bracket set group name
www1.example.org              #Define the monitored host. This can be the host name or IP address. The host name needs to be modified in the / etc/hosts file
www2.example.org:2222     #Define the remote connection port after the colon. The default is port 22 of ssh
If it is a host with similar name, you can use the 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

inventory variable

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

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

[webservers:children]
apache
nginx
  • inventory variable parameter
parameter Explain
ansible_ssh_host The remote host name to be connected. If it is different from the alias of the host you want to set, you can set it through this variable
ansible_ssh_port ssh port number. If it is not the default port number, set it through this variable
ansible_ssh_user Default ssh user name
ansible_ssh_pass SSH password (this is not secure, we strongly recommend using -- ask pass or SSH key)
ansible_ssh_private_key_file The private key file used by SSH. It is applicable to the case where there are multiple keys and you do not want to use SSH proxy
ansible_ssh_common_args This setting is attached to the default command line for sftp, scp, and ssh
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 Determines whether SSH pipes are used. This overrides the setting in ANSI ble.cfg
ansible_shell_type The shell type of the target system. By default, command execution uses' sh 'syntax, which can be set to' csh 'or' fish '
ansible_python_interpreter Python path of the target host. Applicable: there are multiple Python in the system, or the command path is not "/ usr/bin/python", such as * BSD, or / usr/bin/python
ansible_*_interpreter The "*" here can be an interpreter of ruby or perl or other languages, which functions like ansible_python_interpreter
ansible_shell_executable This will set the shell that the ANSI ble controller will use on the target machine, overriding the configuration in ANSI ble.cfg, which defaults to / bin/sh

YAML markup language

YAML: another markup language. It is a language used to write configuration files, which is very concise and powerful.
YAML syntax, like other languages, can also express data structures such as hash table and scalar.
Structure is displayed by spaces; configuration items in sequence are represented by -; key values in Map are separated by; yaml extension is yaml
  • Basic grammatical rules

    1. Case sensitive
     2. Use indent to represent hierarchy
     3. Tab key is not allowed when indenting, 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 structure supported by YAML
    1. Object: set of key value pairs, also known as mapping / hashes / dictionary
     For example: name:Example Developer
        Key value
     2. Array: a set of values arranged in order, also known as sequence / list
     For example: - Apple
       -Orange
     3. Pure quantity: single, indivisible value
     For example: number: 12.30
       sure: true

yaml instance:

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

Ansible script playbook

PlayBook is a completely different way of using ANSI ble, similar to the state file of saltstack. ad-hoc can't be used persistently. Playbook can be used persistently.
PlayBook is a list composed of one or more plays. The main function of play is to dress up the hosts that are merged into a group in advance and define the roles through the tasks in ansible. Fundamentally speaking, the so-called task is nothing more than a module calling ansible. Organizing multiple plays in one playbook allows them to work together to accomplish a task according to a pre arranged mechanism. Call ansible's template through task to organize multiple plays to run in a playbook.

Playbook core elements

Name Meaning
Hosts List of remote hosts executed
Tasks Task set, that is, an operation completed by the calling module
Varniables Variables, built-in variables or custom variables are invoked in playbook.
Templates Templates, i.e. files using template syntax, such as configuration files
Handlers Processor, which is used in combination with notity, is triggered by specific conditions. Only when the conditions are met can the operation be executed, otherwise it will not be executed
tags Tag, which specifies the execution of a task, and is used to select part of the code in the playbook to run
Roles role

Playbook syntax

1. playbook uses yaml syntax format, and the suffix can be yaml or yml.
In a single playbook file, you can distinguish multiple plays with three consecutive hyphens (- --). There are also optional three consecutive dots (...) to indicate the end of play, which can also be omitted.
2. When the line starts to write the content of the playbook normally, the function of the playbook will generally be described.
3. Comment the code with #.
4. Indentation must be unified, and cannot be mixed with space and tab. The indentation level must also be consistent. The same indentation represents the same level. The program judges that the configuration level is realized by combining indentation with line feed.
5. YAML file content and Linux system case judgment are consistent, case sensitive, and the value of k/v should be case sensitive
 6. The value of k/v can be written in the same line or in new line. Peer use: separate. v can be a string or a list
 7. A complete code block function requires a minimum of elements including name: task

Example demonstration:

vim a.yaml

- hosts: webserver                  #Defined host group, i.e. applied host
  vars:                             #Defining variables
    http_port: 80
    max_clients: 200
  user: root
  tasks:                               #Tasks performed
  - name: ensure apache is at the latest version
    yum: pkg=httpd state=latest
  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf
    notify:
    - restart apache
  - name: ensure apache is running
    service: name=httpd state=started
  handlers:                         #processor
    - name: restart apache
      service: name=httpd state=restarted
  • Execute a playbook format
Ansible playbook [yaml filename]

Example demonstration:

#Execution script
ansible-playbook ping.yaml

Parameters:

-k(– ask pass) is used to enter ssh password interactively
 -K (- ask become pass) is used to enter sudo password interactively
 -u designated user

Supplementary order:

#Check whether the syntax of yaml file is correct
ansible-playbook nginx.yaml --syntax-check

#Check tasks
ansible-playbook nginx.yaml --list-task

#Check active hosts
ansible-playbook nginx.yaml --list-hosts

#Specify to run from a task
ansible-playbook nginx.yaml --start-at-task='Copy Nginx.conf'

About hosts and users

Example demonstration:

vim a.yaml

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

#Execution script
ansible-playbook a.yaml 
  • Define remote execution users for each task on the original basis
!vim

- hosts: mysql
  remote_user: root             
  tasks:
    - name: test connection
      ping:
      remote_user: mysql          #Specify mysql as the running user of tasks executed by the remote host

#Execute playbook script
ansible-playbook ping.yml -k 

#Verification syntax
ansible-playbook a.yml --syntax-check

#Execution script
ansible-playbook a.yml 
  • Specify the remote host sudo switch user
!vim

- hosts: mysql
  remote_user: root            
  become: yes                  #Parameters after version 2.6, formerly sudo, means to switch users to run
  become_user: mysql          #Specify sudo user as mysql

#Execute playbook script
ansible-playbook ping.yml -K

#Execution script
ansible-playbook a.yml 

tasks list and action

1. The main part of play is the task list. Each task in the task list is executed on the host specified in hosts one by one in order, that is, the second task is started after the first task is completed on all hosts.
When running playbook (execute from top to bottom), if one host fails to execute the task, the whole tasks will be rolled back. Please correct the errors in playbook and execute again.
The purpose of Task is to execute the module with the specified parameters, while variables can be used in the module parameters. The module execution is idempotent, which means that multiple execution is safe because the results are consistent.
2. Each task must have a name, so when you run playbook, you can tell which task it belongs to from the task execution information it outputs. If no name is defined, the value of 'action' will be used to mark specific tasks in the output information.
3. Define a task in the common format: "module: options", for example: yum: name=httpd
 4. In the native module of ansible, command module and shell module do not need to use key=value format

Example demonstration:

  • Example 1
vim a.yml 

- hosts: webserver
  remote_user: root
  tasks:
   - name: disable selinux
     command: '/sbin/setenforce 0'
   - name: make sure apache is running
     service: name=httpd state=started
#In play, as long as the return value of the executed command is not 0, an error will be reported and tasks will stop

#Check syntax
ansible-playbook a.yml --syntax-check

#Execution script
ansible-playbook a.yml 

#Examination result
rpm -q httpd

Amend the following:

!vim

- hosts: webserver
  remote_user: root
  tasks:
   - name: disable selinux
     command: '/sbin/setenforce 0'
     ignore_errors: True             #Ignore the error and force to return success
   - name: make sure apache is running
     service: name=httpd state=started

#Check syntax
ansible-playbook a.yml --syntax-check

#Execution script
ansible-playbook a.yml 
  • Example 2
vim b.yml 

- 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

#Check syntax
ansible-playbook b.yml --syntax-check

#Execution script
ansible-playbook b.yml

Introduction to Handlers

Handlers are also lists of some tasks, which are no different from general tasks.
notify is performed by the notifier. If not, Handlers will not be executed. If not, Handlers will be executed
 No matter how many notifiers notify, after all task s in play are executed, handlers will only be executed once

Example demonstration:

vim c.yml

- 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

#Check syntax
ansible-playbook c.yml --syntax-check

#Execution script
ansible-playbook c.yml

Some variables can also be introduced:

!vim

- 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

#Check syntax
ansible-playbook c.yml --syntax-check

#Execution script
ansible-playbook c.yml

How to use variables in playbook

1. Pass through ansible command

Example demonstration:

#Edit the following yml
vim a.yml

- hosts: mysql
  remote_user: root
  vars:
  - user:
  tasks:
  - name: add new user
    user: name={{user}}

#Execution script
ansible-playbook a.yml -e "user=testvar"

#Execute command to view file
ansible mysql -m command -a 'tail /etc/passwd'

2. Define variables directly in yaml -- for example, handlers

3. Direct reference to some variables

Example demonstration:

  • Fixed variable referencing ansible
vim test.yml

- hosts: mysql
  remote_user: root
  tasks:
   - name: copy file
     copy: content="{{ansible_all_ipv4_addresses}}," dest=/opt/vars.txt

#Execution script
ansible-playbook test.yml

#View the contents of the vars.txt file on the 122 host
cat /opt/vars.txt
  • Reference host variable
vim /etc/ansible/hosts

#Add the following after the host of mysql group
[mysql]
192.168.142.122 testvar="42.122"    #The value defining the testvar variable is 42.122

vim 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

#Execution script
ansible-playbook test.yml

#View the contents of the vars.txt file on the 122 host
cat /opt/vars.txt

Condition testing

If you need to use conditional tests according to variables, facts (setup) or the execution results of previous tasks as a prerequisite for the execution of a task, use the when clause in Playbook.
You can use conditional tests by adding a when clause after a task: the when clause supports regular expressions or syntax.

Example demonstration:

vim when.yml

- hosts: mysql
  remote_user: root
  tasks:
    - name: "shutdown CentOS"
      command: /sbin/shutdown -h now
      when: ansible_distribution == "CentOS"

#Execute the script. After execution, it will be found that the 192.168.142.122 host has been shut down
ansible-playbook when.yml 
  • Multi condition judgment
vim 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"

#Execution script
ansible-playbook when.yml 
  • Group condition judgment
vim 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")

#Execution script
ansible-playbook when.yml 
  • Custom variables for conditional testing
vim when.yml

- hosts: all
  vars:
    exist: "True"
  tasks:
  - name: creaet file
    command:  touch /tmp/test.txt
    when: exist | match("True")

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

#Execution script
ansible-playbook when.yml 

iteration

The iterative mechanism can be used when there are tasks that need to be executed repeatedly. The format is to define the content to be iterated as item variable reference, and indicate the iterated element list through with items statement.

Example demonstration:

vim  d.yml

- hosts: webserver
  remote_user: root
  tasks:
    - name: "Install Packages"
      yum: name={{ item }} state=latest
      with_items:
        - httpd
        - mysql-server
        - php

#Check syntax
ansible-playbook d.yml --syntax-check

#Execution script
ansible-playbook d.yml

#See if there are users specified to add on all hosts
tail -5 /etc/passwd

It can also be defined by itself:

vim e.yml

- 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'}

#Check syntax
ansible-playbook e.yml --syntax-check

#Execution script
ansible-playbook e.yml

#See if there are users specified to add on all hosts
tail -5 /etc/passwd

Templates module

#Create working directory
mkdir templates

#Copy profile
cp /etc/httpd/conf/httpd.conf templates/httpd.conf.02

#Modify httpd.conf.02 file
vim templates/httpd.conf.02
Listen {{http_port}}
ServerName {{ansible_fqdn}}
MaxClients {{maxClients}}

#Modify the ansible/hosts file
vim /etc/ansible/hosts
[webserver]
192.168.142.121 http_port=80 maxClients=100
192.168.142.122 http_port=8080 maxClients=200

#Script writing
vim apache.yml

- 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
     template: src=/root/templates/httpd.conf.2 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

#Check syntax
ansible-playbook e.yml --syntax-check

#Execution script
ansible-playbook apache.yml
#View on two managed servers
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 tasks. If we only want to execute one or more tasks, we can use the tags function.
The format is as follows:
vim 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

#Check syntax
ansible-playbook e.yml --syntax-check

#Execution script
ansible-playbook hosts.yml --tags="only"
ansible-playbook hosts.ym
In fact, it's not just possible to specify the same tags for a single or multiple tasks. playbook also provides a special tags for always. The function is that when using "always" as the task of the tags, no matter which one is executed, the tags defined with "always" will be executed.

Example demonstration:

vim 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

#Check syntax
ansible-playbook e.yml --syntax-check

#In order not to affect this operation, delete the / opt/hosts file in the remote host
rm -rf /opt/hosts 

#Execution script
ansible-playbook hosts.yml --tags="only"
#View the file creation on two managed servers
ls /opt/

Thank you for reading!!!

Posted by Arez on Mon, 03 Feb 2020 09:08:23 -0800