Automated Operations and Maintenance Tool Ansible-playbook Details and Case Actual

1. playbook - Introduction to playbook

playbooks is a different mode of execution from the Ansible command line, which is more flexible and powerful.Simply put, playbook is a very simple configuration management and multi-host deployment system that, unlike any existing pattern, serves as a foundation for deploying complex applications.Playbook can be customized and executed in an orderly manner according to specified operational steps, supporting both synchronous and asynchronous approaches.It is worth noting that playbook is defined as a description in YAML format.

1.1, Core Elements

  1. Hosts: list of remote hosts executed
  2. Tasks: tasks, list of actions defined by the template
  3. variables: variable, built-in variable or custom variable called in playboook
  4. templates: Template, a file that uses the template syntax; replaces variables in the template and implements some simple logic while the file
  5. handlers: Processor, used in conjunction with notify; triggers action when a condition is met
  6. Tags: Tags that specify the conditions under which a part of the code in the playbook is selected to run.Ansible is idempotent, so it automatically skips unchanged parts, even though some code will take a long time to test that it does not change.At this point, if you are sure it hasn't changed, you can skip these snippets with tags
  7. roles: role
    ansible-playbook -t tagsname useradd.yaml

    1.2. Basic Components

  8. The purpose of each play in hosts:playbook is to have one or more hosts perform tasks as a specified user identity.Hosts used to specify tasks must be defined in the host list beforehand
    The form is as follows:
    hosts: websrvs
  9. remote_user: Can be used in hosts and tasks, or can be executed on a remote host by specifying sudo, which can be used for paly global or a task, and can even be used to specify the user to switch when sudo is sudo using sudo_user
    The form is as follows:
    hosts: 192.168.16.10
    remote_user: root

tasks:
name: test connection
ping:
remote_user: root
sudo: yes
sudo_user: root

 3. tasks: Task list; there are two formats:
 action: module argument
 Module: argumentRecommended                                                                                                    
Note: The shell and command modules are followed by commands, not key=value
 When the status of a task changes after running, the handlers can be notified by'notify'
Tasks can be tagged with'tags'and then invoked with the -t specification on the absible-playbook command
 Example:

```bash
tasks:
  - name: disable selinux
    command: /sbin/setenforce 0

If the exit code of a command or script is not zero, you can replace it with one

tasks: 
  - name: run this command and ignore the result
    shell: /usr/bin/somecommand || /bin/true

perhaps

tasks: 
  - name: run this command and ignore the result
    shell: /usr/bin/somecommand
    ignore_errors: True

1.3, yaml syntax

The syntax of YAML is similar to other high-level languages and can simply represent data structures such as lists, hashes, scalars, etc. Its structure is represented by spaces.(Lists are represented by horizontal bars, key-value pairs are separated by colons, and key-value pairs can be nested inside other key-value pairs)
The yaml file extension is usually.yaml or.yml.Here's an example
Align with spaces only

name: wkx   #Space after colon
age: 28
gender: male
spouse:
  name: rlt
  age: 27
  gender: female
children:
  - name: dabao   #Space behind horizontal bar
    age: 4
    gender: femle
  - name: xiaobao
    age: 1
gender: male

1.4. How playbook works

ansible-playbook <filename.yaml> ... [options]
Common options:
--check detects only possible changes, but does not actually perform the operation
--list-hosts Lists the hosts running the task
--limit host list, executed only for hosts in host list
-v Display Procedure-v V-V V More Details
ansible-playbook file.yaml --check detects only
Ansible-playbook file.yaml execution
Ansible-playbook file.yaml --limit websevs executed only by websevs host

1.5,Playbook VS shellscript

Shell script

#!/bin/bash
# install apache
yum -y install httpd
#copy conf file
cp /tmp/http.conf /etc/httpd/conf/httpd.conf
#start service
systemctl enable httpd 
systemctl start httpd 

Palybook

- hosts: wensevs
  remote_user: root

  tasks:
   - name: install apache
     yum: name=httpd

   - name: copy conf file
     copy: src=/tmp/http.conf dest=/etc/httpd/conf/httpd.conf 

   - name: start service
     service: name=httpd state=started enabled=yes

2. Combining handles with notify

Handlers: is a list of task s that are not essentially different from the previous ones and are used to take action when the resources of interest change
Notify: This action is used to trigger each play at the end, which prevents the specified action from being executed each time multiple changes occur and completes the specified action once after all the changes have occurred.The operations listed in the notify are called handlers, which call the operations defined in the handler in the notify.
Example:
Use of Handles and notify:

- hosts: websrvs
  remote_user: root

  tasks:
   - name: add group nginx
     tags: user
     user: name=nginx state=present

   - name: add user nginx
     group: name=nginx state=present group=nginx

   - name: install nginx
     yum: name=nginx state=present

   - name: copy file
     copy: src=/tmp/nginx.conf dest=/etc/nginx/nginx.conf
     notify:
      - restart nginx
      - check nginx process
    handlers:
     - name: restart nginx    #Must match the name defined in notify
       service: name=nginx status=restarted enabled=yes
     - check nginx process
       shell: killall -0 nginx > /tmp/nginx.log

Use of Tags

 1. hosts: wensrvs
  remote_user: root

  tasks:
 2. name: install httpd
     yum: name=httpd status=present

 3. name: copy conf file
     copy: src=files/httpd.conf dest=/etc/httpd/conf/httpd.conf
     tags: conf

 4. name: start service
     tags: service
     service: name=httpd state=started enabled=yes

3. Use of variables in playbook

3.1, Variables

Variable name: can only consist of letters, numbers, and underscores, and can only begin with a letter
Variable Source:

  1. Variables under the ansible setup module can be used
  2. /etc/ansible/hosts
    Common variables: Hosts in a host group are defined separately and take precedence over common variables
    Common group variables: Define uniform variables for all hosts in a host group
  3. Priority is best when specifying variables from the command line
    ansible-playbook -e varname=value
  4. Define in playbook
    var:
    var1: value1
    var2: value2
  5. Define in role

3.2. How variables are called

  1. Variables are called through {{variable_name}} and must have spaces before and after the variable name, sometimes using'{variable_name}}'to take effect
  2. Anible-playbook-e option specifies
    ansible-playbook -e "hosts=www user=wkx" test.yaml

    3.3. Using variables

  3. Using variable files
cat vars.yaml 
var1: httpd
var2: nginx

cat var.yaml
- hosts: 192.168.16.115
  remote_user: root
  vars_files:
    - vars.yaml
  tasks:
    - name: touch httpd.txt
      file: name={{var1}}.txt state=touch   #Create by default under current user
    - name: touch nginx.log
      file: name={{var2}}.log state=touch

  1. Use setup variable

    cat var.yaml
    - hosts: 192.168.16.115
    remote_user: root
    
    tasks:
    - name: create log file
      file: name=/root/ansible-test/{{ ansible_fqdn }} state=touch  #{{ansible_fqdn}} is a built-in variable for domain names in the setup module

  2. Command Line Use Variables

    cat var.yaml
    - hosts: 192.168.16.115
    remote_user: root
    
    tasks:
    - name: create log file
      file: name=/root/ansible-test/{{ pkg }} state=touch

    ansible-playbook -e pkg=haha var.yaml

  3. Variables in hosts (/etc/asible/hosts)
    [websrvs:vars]  #Common (group) variables
    mark="-"
    [websrvs]   #Common variable
    192.168.16.115 hname=wg sname=115
    192.168.16.118 hname=wg sname=118

    ansible websrvs -m hostname -a 'name= {{ hname }}{{ mark }}16{{ mark }}{{sname}}'

    3.4, Template file templetes

    Text files, nested scripts (written in a template programming language)
    Jinja2 voice, using literal quantities, in the following form
    String: Use single or double quotation marks
    Numbers: Integers, Floating Points
    List: [haha,xixi,hehe,lele]
    Tuple: (haha,xixi,hehe,lele)
    Dictionary: {name:wkx,gender:male}
    Boolean: true, false
    Arithmetic operations: +, -, *, /, //,%, ** are addition, subtraction, multiplication, division, integer, and division power, respectively
    Comparison operation: ==,!=,>,<,>=,<=
    Logical operations: and,or,not
    Stream expression: for,if,when

  4. When
    Conditional Testing: If you need to use a conditional test as a precondition for a task to execute or not based on variables, facts, or the results of previous tasks, using the when statement, in task, the syntax format of jinja2
    Example:
cat var.yaml
- hosts: 192.168.16.115
 remote_user: root

  tasks:
  - name: "create file"
   file: name="/root/ansible-test/xixi" state=touch
   when: ansible_os_family == "RedHat"

  1. Iterative Nested Independent Variables
    Example 1:
- hosts: 192.168.16.115
  remote_user: root

  tasks:
  - name: "create some file"
    file: name=/root/ansible-test/{{ item }} state=touch  #Create a file with nested variables below
    when: ansible_distribution_major_version == "7"  #Match condition, execute when condition is satisfied
    with_items:
      - haha
      - xixi
      - lele
  - name: install some packages
    yum: name={{ item }}
    with_items:
      - lrzsz
      - net-tools


Example 2:

cat user.yaml 
- hosts: 192.168.16.115
  remote_user: root

  tasks:
  - name: "create some group"
    group: name={{ item }}
    when: ansible_distribution_major_version == "7"
    with_items:
      - g1
      - g2
      - g3
  - name: cerate user
    user: name={{ item.name }} group={{ item.group }}
    with_items:
      - { name: "user1",group: "g1"}
      - { name: "user2",group: "g2"}
      - { name: "user3",group: "g3"}


template for if in Playbook

{% for vhost in nginx_vhosts %}
server{
listen {{ vhost.listen | default('80 default_server')}};

{% if vhost.server_name is defined %}
Server_name{{ vhost.server_name }};
{% endif %}

{% if vhost.root is defined %}
root {{ vhost.root }}
{% endif %}

Example 1:

cat temnginx.yaml
---
- hosts: websrvs
remote_user: root
vars:
  nginx_hosts:
    - 80
    - 8088
    - 
tasks:
  - name: templete config
    template: src=/root/ansible-test/nginx.conf.j2 dest=/root/nginx.conf

cat nginx.conf.j2
{% for vhost in nginx_hosts %}
server {
  listen {{ vhost }}
}
{% endfor %}

Generate as file as

cat /root/nginx.conf
server {
  listen 80
}
server {
  listen 8088
}


Example 2:

cat temnginx.yaml
---
- hosts: websrvs
  remote_user: root
  vars:
    nginx_hosts:
      - web1:
        listen: 8080
        root: "/var/www/nginx/web1/"
      - web2:
        listen: 8080
        server_name: "www.wkx.com"
        root: "/var/www/nginx/web2/"

  tasks:
    - name: templete config
      template: src=/root/ansible-test/nginx.conf.j2 dest=/root/nginx.conf
cat nginx.conf.j2
{% for vhost in nginx_hosts %}
server {
  listen {{ vhost.listen }}
  {% if vhost.server_name is defined %}
  server_name {{ vhost.server_name }}
  {% endif %}
  root {{ vhost.root }} 
}
{% endfor %}

4. Batch installation of zabbix-agent via ansible-playbook

cat zabbix-agent.yml

- hosts: agent
  remote_user: root

  tasks:
   - name: copy zabbix-agent
     copy: src=/mnt/zabbix-agent-4.4.0-1.el7.x86_64.rpm dest=/tmp

   - name: install zabbix-agent
     yum: name=/tmp/zabbix-agent-4.4.0-1.el7.x86_64.rpm

   - name: copy config
     copy: src=/etc/zabbix/zabbix_agentd.conf dest=/etc/zabbix/zabbix_agentd.conf

   - name: modify conf hostname
     lineinfile:
     path: /etc/zabbix/zabbix_agentd.conf
     regexp: "^Hostname"
     line: "Hostname={{ansible_hostname}}"

   - name: start zabbix-agent
     service: name=zabbix-agent state=started enabled=yes





5,role

New features introduced by ansible since version 1.2.Playbook is a hierarchical, structured organization.Roles can automatically load variable files, tasks, handlers, and so on, depending on the hierarchy.To use roles, you only need to use the include directive in playbook.Simply put, roles is a mechanism for including variables, files, tasks, templates, and processors in separate directories and easily.Roles are typically used in scenarios where services are built based on the host structure, but they can also be used in scenarios such as building daemons.

Complex scenarios: roles are recommended for high code reuse
Change host and host group
Such as irregular naming or high cost of inheritance
Some functions require multiple playbook s, which are implemented through include
Ansible's roles directory structure
Each role, organized in a specific hierarchical directory structure

Roles Directory structure:
playbook.yaml
roles/
project/   Project name with the following subdirectories
tasks/  Definition task,role Basic element containing at least one named main.yaml Files; other required files are passed here include Include
files/  Stored by copy perhaps script File called by module
vars/ Not common, define variables; contains at least one named main.yaml Files; other required files are passed here include Include
default/ Not common, use this directory when setting default variables main.yaml
templates/  template The module looks for the directory of the template question file needed
handlers/
meta/  Not common, defining special settings and dependencies for the current role; contains at least one named main.yaml Files; other required files are passed here include Include

Tags: Unix Nginx ansible Zabbix yum

Posted on Sun, 12 Apr 2020 09:44:13 -0700 by susi