Ansible automation operation and maintenance foundation ------- ploybook

Posted by Grodo on Sat, 18 Dec 2021 10:41:24 +0100

Premise summary: This article is https://blog.csdn.net/kali_yao/article/details/119983133 Advanced plate

catalogue

I Introduction and usage of ploybook

1. Overview of ploubook:

2. What is yaml?  

3.Playbook syntax format requirements are as follows:

II Usage cases

1. Write the first Playbook (script)

2. User management, create system account, account attribute and set password

3. Use playbook to manage logical volumes

4. Use playbook management software

5. Firewall policy configured for firewalld module

6.template module

7. Application case of ansible variable

8. Method of defining variables

III Ansible advanced syntax application

1.error handling

2.handlers

3.when condition judgment

4.block task block

5.always statementdefines the tasks to be executed regardless of whether the block task is successful or not

6.loop loop loop

IV Ansible Roles role

1. Introduction to roles

2. Introduction to roles directory

3. Create a simple role

Ansible ad-hoc can remotely manage other hosts in the form of command line, which is suitable for performing some temporary simple tasks. In addition, there is a remote management method called Playbook. The Chinese name of Ansible Playbook is script. It writes the tasks that often need to be performed into a file, which is called script.

I Introduction and usage of ploybook

1. Overview of ploubook:

A script can contain multiple tasks

After the script is written, we execute relevant task orders according to the script at any time

Playbook scripts are required to be written in YAML format

Suitable for performing complex tasks that are performed periodically and frequently

2. What is yaml?  

YAML is a highly readable format language used to express data sequences

YAML: YAML Ain't a Markup Language

YAML takes data as the center and focuses on describing the relationship and structure of data

YAML format requirements are as follows:

"#" stands for notes. Generally, the first line is three horizontal bars (- --)

The key/value pair is represented by ":", the array is represented by "-", and there is a space after "-"

key and value are separated by ":", and there must be a space after ":

Generally, indentation consists of two or more spaces

Indents at the same level must be aligned, and indents represent hierarchical relationships

The tab key cannot be used for full text

Case sensitive

The extension is yml or yaml

Cross row data needs to use > or | where | will retain line breaks

YAML official website: http://www.yaml.org

3.Playbook syntax format requirements are as follows:

playbook is written in YAML format

The playbook file consists of one or more plays. Each play can contain elements such as hosts, tasks, and vars

Run the playbook script using the ansible playbook command

II Usage cases

1. Write the first Playbook (script)

hosts, tasks, and name are keywords (not modifiable). ping is a module that calls different modules to complete different tasks.

vim ~/ansible/test.yml
---
- hosts: all                                #hosts defines who to remote?
  tasks:                                    #Tasks what are the tasks to be performed after defining remote?
      - name: This is my first playbook      #The specific content after name can be arbitrary
        ping:

ansible-playbook ~/ansible/test.yml # operation

 ansible-playbook ~/ansible/test.yml -- check # only detects and does not run

2. User management, create system account, account attribute and set password

vim ~/ansible/test_john.yml
---
- hosts: webserver
  tasks:
    - name: Add the user 'johnd' 
      user:
        name: johnd
        uid: 1040
        group: daemon
        shell: /bin/bash
        groups: bin,adm
        password: "{{ '123' | password_hash('sha512') }}"

3. Use playbook to manage logical volumes

 vim ~/ansible/lvm.yml
---
- hosts: node2                     #Remote node2 host
  tasks:
    - name: Create a new primary partition with a size of 1GiB  #Description of the task
      parted:                      #Call the parted module to partition         
        device: /dev/vdb           #Partition the / dev/vdb disk (do not copy the disk name)
        label: gpt                 #The partition table type is gpt or msdos
        number: 1                  #Zone number (which zone to create)
        state: present             #present is to create a partition, and absent is to delete a partition
        part_start: 1MiB           #The start position of the partition (the default is to partition from the start position)
        part_end: 1GiB             #The end position of the partition (to the last position of the disk without writing)
    - name: Create a volume group on top of /dev/vdb1   #Description of the second task
      lvg:                          #Call lvg module to create VG volume group
        vg: my_vg                   #The name of the volume group to create
        pvs: /dev/vdb1              #Which partition is used to create PV
    - name: Create a logical volume of 512m          #Description of the third task
      lvol:                          #Call lvol module to create LV
        vg: my_vg                    #Which VG is used to create LV
        lv: my_lv                    #LV name to be created
        size: 512m                   #The LV size to be created can not be specified. The default unit is m
    - filesystem:                     #format partition 
         fstype: ext4                #Format type
         dev: /dev/sdb1              #Which disk
         force: true                 #Enforcement

4. Use playbook management software

---
- hosts: webserver                #Who needs a remote host
  tasks:                          #Define the tasks that the script needs to perform
    - name: Install a list of packages  #Description of the first task 
      yum:                              #Call yum module to install the software
        name:                           #The name of the installation software. It has multiple values. Use array-
          - httpd                       #Install httpd software
          - mariadb                     #Install mariadb software
          - mariadb-server              #Install MariaDB server
    - name: install the 'RPM Development Tools' package group   #Description of the second task
      yum:                              #Call yum module to install the package
        name: "@RPM Development Tools"  #Which package to install, @ is the keyword
    - name: update software             #Description of the third task
      yum:                              #Call yum module to upgrade the software
        name: '*'                       #What software needs to be upgraded
        state: latest                   #latest stands for software upgrade

5. Firewall policy configured for firewalld module

---
- hosts: test                        #hosts defines the host that needs to be remote
  tasks:                             #Tasks defines which tasks need to be performed
    - name: install firewalld.        #name defines the description information for the first task
      yum:                           #The first task calls the yum module to install the software
        name: firewalld               #The name of the software to be installed is firewalld
        state: present               #state equals present to install the software
    - name: run firewalld.            #Define the description of the second task
      service:                       #The second task calls the service module to start the service
        name: firewalld               #The service name started is firewalld
        state: started               #state equals started to start the service
        enabled: yes                 #enabled equals yes to set the service to start automatically
    - name: set firewalld rule.       #Description of the third task
      firewalld:                      #The third task calls the firewalld module to set firewall rules
        port: 80/tcp                #Add a rule to release tcp and port 80 in the firewall rule
        permanent: yes              #permanent is to set persistent rules
        immediate: yes              #immediate is to make the rule take effect immediately
        state: enabled              #state equals enabled to add firewall rules

6.template module

The copy module can copy a file to a remote host, but what if you want the contents of each copied file to be different? How to copy index. To all web hosts HTML content is the respective IP address?

Ansible can use Jinja2 template engine to read variables. Before calling variables in playbook, it is also a function of Jinja2. The expression of Jinja2 module is contained in the delimiter "

 vim ~/ansible/index.html  #Create a file and write its contents
Welcome to {{ansible_hostname}} on {{ ansible_eth0.ipv4.address }}. 



vim ~/ansible/template.yml
---
- hosts: webserver
  tasks:
    - name: use template copy index.html to webserver.
      template:                                   #Copy file
        src: ~/ansible/index.html                 #Original document
        dest: /tmp/index.html                     #target

7. Application case of ansible variable

1) setup module

ansible_facts is used to collect the system information of managed devices. All collected information is saved in variables. By default, the first task is collecting facts every time playbook is executed. You can view the collected facts information using the setup module. That is, all environment variables

ansible test -m setup

2) debug module

The debug module can display the value of variables and assist in troubleshooting. The value of variables can be displayed through msg. Variables need to be expanded with {}}.

---
- hosts: test
  tasks:
    - debug:
        msg: "The host name is:{{ ansible_hostname }}"
    - debug:
        msg: "Total memory size:{{ ansible_memtotal_mb }}"

8. Method of defining variables

Ansible supports more than a dozen ways to define variables. Here we will only introduce some of them.

The following is the definition method of sorting according to priority:

The Inventory variable specifies a variable for the host Inventory

Host Facts variable - Host Facts variable

Playbook variables are variables in the script

The variable file priority set starts with the variable file

1) ) the Inventory variable (defined in the host Inventory configuration file) is not in yml format.

vim ~/ansible/inventory
[test]
node1  iname="nb" 
[proxy]
node2
[webserver]
node[3:4]
[webserver:vars](Immutable variable)
iname="dachui"
---
- hosts: node1,webserver                      #Define who hosts need to be remotely managed               
  tasks:                                      #What are the tasks of the play
    - name: create a user with var.           #Description information of the first task in the play
      user:                                   #Call the user module to create a user
        name: "{{ iname }}"                   #The user name to be created is the variable iname

#In the ansible script, when you call a variable, you need to add double quotes outside {} to call the variable at the beginning

#If the variable {}} is called in the back or middle position, double quotation marks can be added or not

2) Host Facts variable (you can directly call ansible to collect system information)

---
- hosts: test
  tasks:
    - name: create user.
      user:
        name: "{{ansible_hostname}}"

#Define the script, remote all managed hosts, call the user module, and create users

#The user name that needs to be created is ansible_hostname is an ansible_facts variable

3) PlayBook variables (variables can be defined in playbook using vars keyword)

---
- hosts: test
  vars:                                     #vars is a keyword used to define variables
    iname: heal                            #The specific variable name is iname and the value is heal
    ipass: '123456'                       #Define a variable named ipass with a value of 123456
#Note that the password must be a string and quotes are required                           
  tasks:                                   #Tasks defines the tasks to be performed
    - name: Use variables create user.  #Write a description of the task   
      user:                                #Call the user module to create a user
        name: "{{ iname }}"               #The user name is the previously defined variable
        password: "{{ ipass | password_hash('sha512') }}"

4) Define a variable file separately

 vim  ~/ansible/variables.yml
---
iname: cloud
ipass: '123456'

Using vars in playbook_ Files calls the file

---
- hosts: test
  vars_files: variables.yml             #When there are many variables, a file is specially defined to store variables
  tasks:
    - name: create user.
      user:
        name: "{{ iname }}"
        password: "{{ ipass | password_hash('sha512') }}"

III Ansible advanced syntax application

1.error handling

By default, ansible will stop the playbook immediately when it encounters an error and use ignore_errors you can ignore the error and continue with subsequent tasks.

---
- hosts: test
  tasks:
    - name: start a service that does not exist.
      service:
        name: hehe
        state: started
      ignore_errors: true       #Ignore errors for a task (ignore_errors is the keyword)                          
    - name: touch a file.        # Ignored = 1 (ignore 1)
      file:
        path: /tmp/service.txt
        state: touch
---
- hosts: test
  ignore_errors: true      #Ignore errors globally for playbook                             
  tasks:
    - name: start a service that does not exist.
      service:
        name: hehe
        state: started
    - name: touch a file.
      file:
        path: /tmp/service.txt
        state: touch

2.handlers

In the script, tasks are used to define tasks (which must be executed), and handlers can also define tasks (which do not have to be executed). To execute a handler task, it must be triggered by others

---
- hosts: test
  tasks:(Execute in a certain order)
    - Task 1
       notify:Task 5 (only if the first one is executed and yellow, then execute [green no])
    - Task 2
  handlers:(Not necessarily implemented) (only if it is implemented in the front and yellow [green can't])
    - Task 5 (when the same task is executed only once and in tasks (execute after execution)
    - Task 6

3.when condition judgment

When can define judgment conditions. A task is executed only when the condition is true. Common condition operators are: = =,! =, >, > =, <, < =. Mu lt iple conditions can be split by using and (or) or or (or), and the variable is not used in when expression.

---
- hosts: test
  tasks:
    - name: check memory size.
      service:
        name: NetworkManager
        state: stopped
      when: ansible_memfree_mb < 700

#If the remaining memory of the managed host is less than 700M, close the NetworkManager service (or other unnecessary services) skipped = 1 (skip one)

4.block task block

If we need to execute N tasks when the conditions are met, we can add when judgment to all N tasks (but it is troublesome). At this time, we can use block to define a task block, and execute the whole task block when the conditions are met

Task block is to merge a group of tasks into a task group. Multiple tasks can be merged into a task group using block statement.

---
- hosts: test
  tasks:
    - name: define a group of tasks.
      block:                                          #block is a keyword that defines a task group
        - name: install httpd                       #The first task in the task group
          yum:                                        #Call the yum module to install the httpd package
            name: httpd
            state: present
        - name: start httpd                          #The second task in the task group
          service:                                    #Call the service module to start the httpd service
            name: httpd
            state: started
      when: ansible_distribution == "RedHat"       #Execute the task group only if the conditions are met

Note: when and block are aligned. They are at the same level. When the conditions are met, the task group (not a task) is to be executed

5.always statementdefines the tasks to be executed regardless of whether the block task is successful or not

---
- hosts: test
  tasks:
    - block:
        - name: touch a file test1.txt
          file:
            name: /tmp/test1.txt      #If it is modified to / TMP / XYZ / test1 Txt cannot be created successfully                        
            state: touch
      rescue:(block Success is rescue fail)((otherwise)
        - name: touch a file test2.txt
          file:
            name: /tmp/test2.txt
            state: touch
      always:(Always execute)
        - name: touch a file test3.txt
          file:
            name: /tmp/test3.txt
            state: touch

Master: Ansible executes from top to bottom

6.loop loop loop

How to deal with the same module that needs to be executed repeatedly? Using loop loops can avoid repetition

---
- hosts: test
  tasks:
    - name: mkdir multi directory.
      file:
        path=/tmp/{{item}}       #Note that item is the keyword that calls the value of the loop loop loop                                
        state=directory  (The current version can still be written like this)
      loop:                       #Loop is a keyword that defines the value of the loop. Here are the specific values
        - School
        - Legend
        - Life

IV Ansible Roles role

1. Introduction to roles

In order to achieve different functions, we will write a large number of playbook files. Moreover, each playbook may also call other files (such as variable files). It is very painful to manage massive and irregular files!

Ansible supports role from version 1.2. Role is a specification (directory structure) for managing ansible files. Role (role) will automatically read data from specific directories and files according to the standard specification.

If we create a file named user Example, the standard directory structure is as follows

2. Introduction to roles directory

defualts/main.yml: defines the default value of the variable with lower priority
vars/main.yml: define variables with high priority
Files directory: the directory where static files are stored, such as tar package, music, video, etc
templates Directory: where dynamic data files are stored (template files containing variables in the files)
meta/main.yml: description information such as author, version, etc
README.md: description of the entire role
handlers/main.yml: define handlers
tasks/main.yml: where tasks are defined

3. Create a simple role

Public Roles warehouse( https://galaxy.ansible.com )Manage

1) Create directory
mkdir ~/ansible/roles

2) Create role

Using ansible Galaxy install, you can download roles directly or write requirements Download Role from YML file.

For example, direct ansible Galaxy init ~ / ansible/roles/issue

script

#Format 1: it can be downloaded directly from Ansible Galaxy official website
- src: acandid.httpd
#Format 2: it can be downloaded from a git server
- src: http://gitlab.com/xxx/xxx.git
  scm: git
  version: 56e00a54
  name: nginx-acme
#Format 3: tar package can be downloaded from a specified location, supporting http, https and file
- src:  http://example.com/myrole.tar
  name:  myrole

[root@control ansible]# ansible-galaxy install \
-r ~/ansible/roles/requirements.yml \
-p roles
# -r followed by the file name, which contains which role s to download and their link locations
# -p specifies which directory to save the downloaded role to

Topics: Linux Operation & Maintenance