Ansible host list and playbook script

1, Host list

The default host list for ansible is the / etc/ansible/hosts file
The host list can be set manually or generated dynamically through Dynamic Inventory
FQDN is generally used for host names

vi /etc/ansible/hosts
[webserver]              #Set the group name using square brackets
www1.example.org         #Define the monitored host, which can be either host name or IP address
www2.example.org:2222    #The remote connection port is defined after the colon. The default is port 22 of ssh

If you are a host with a similar name, you can use a list to identify each host

[webserver]
//[01:50] indicates a match from 01 to 50, followed by built-in variables. Here, the user name and password for ssh access are defined for interactive login free
www[01:50].example.org ansible_ssh_user=root ansible_ssh_pass=abc123

[dbbservers]
//[a:f] indicates that matching a to f is supported
db-[a:f].example.org

inventory variable parameter

ansible_ssh_host #If the remote host name to be connected 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 #The default ssh user name.
ansible_ssh_pass #SSH password (this method is not secure. It is strongly recommended to use -- ask pass or SSH key).
ansible_ssh_private_key_file #The private key file used by SSH is applicable to the case where there are multiple keys but you don't want to use SSH proxy.
ansible_ssh_common_args #This setting is appended to the default command line for sftp, scp, and ssh.
ansible_sftp_extra_args #This setting is appended to the default sftp command line.
ansible_scp_extra_args #This setting is appended to the default scp command line.
ansible_ssh_extra_args #This setting is appended to the default ssh command line.
ansible_ssh_pipelining #Determine whether to use SSH pipes. This can override ansible CFG.
ansible_shell_type #The shell type of the target system. By default, the command is executed using 'sh' syntax, which can be set to 'csh' or 'fish'.
ansible_python_interpreter #The python path of the target host Applicable to: 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, and can be used as an ansible_ python_ Similar to interpreter.
ansible_shell_executable #This sets the shell that the ANSI BIE controller will use on the target machine, overriding ANSI ble The configuration in CFG defaults to / bin/sh.

Variables in Inventory

Host variable
[webserver]
//Define variable http_port (open port information) and maxRequestsChild (maximum number of processes)
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

#Define a group name and put the two group names just defined into the web server group, that is, the host containing apache group and nginx group
[webservers]
apache
nginx

2, YAML

YAML: another markup language. It is a language for writing configuration files. It is very concise and powerful.
Like other languages, YAML syntax can also express data structures such as hash tables and scalars.
The structure is displayed by spaces; Configuration items in the sequence are represented by -; The key values in the Map are separated by:; yaml has an extension of yaml

1. Basic grammar rules

(1) Case sensitive
(2) Use indentation to represent hierarchical relationships
(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

2. Data structures supported by yaml

object
A collection of key value pairs, also known as mapping / hashes / dictionary

give an example: name (key): Example(value)

class class: (Items)
  Object 1: (table)
    Attribute (name, length, width, height)
    Method (verb, put things)
    ...
  Object 2
  Object 3

array
A set of values arranged in order, also known as sequence / list

give an example:-Apple
     -Orange

Pure quantity
Single, non separable value

give an example: number: 12.30
     sure: true

3, playbook

Call the ansible template through task to organize multiple plays to run in one playbook.

1. Components

Tasks: tasks, that is, an operation completed by the calling module; The principle is the same as that of transactions, either executed together or not executed together.

Variables: variables; There are three scenarios for declaring variables: defined in the hosts file, defined in the script, and - e defined in the command.

Templates: templates; Define the template in the same format to solve the problem that each service may be incompatible due to different formats.

Handlers: the processor that triggers the execution of operations when certain conditions are met.

Roles: role; The tasks are classified and executed without interference with each other.

give an example

cd /opt
vim test1.yaml
---     #Yaml file starts with - -- to indicate that this is a yaml file and can be omitted
- name: first play     #Define the name of a play, which can be omitted
  gather_facts: false    #Set not to collect facts information, which can speed up the execution speed and can be omitted
  hosts: webservers    #Specify the managed host groups to perform tasks. For example, multiple host groups are separated by colons
  remote_user: root    #Specifies the user who performs tasks on the managed host
  tasks:     #Define the task list. Each task in the task list is executed on the host specified in hosts one by one in order
   - name: test connection    #Custom task name
     ping:     #Use the format of module: [options] to define a task
   - name: disable selinux
     command: '/sbin/setenforce 0'    #The command module and shell module do not need to use the key=value format
     ignore_errors: True     #If the return value of the command is not 0, an error will be reported and tasks will stop. You can use ignore_errors ignore failed tasks
   - name: disable firewalld
     service: name=firewalld state=stopped    #The task is defined in the format of module: options, and the option is in the format of key=value
   - name: install httpd
     yum: name=httpd state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf    #You need a prepared / opt / httpd Conf file
     notify: "restart httpd"    #If the status is changed after the above operation, the handlers operation of the corresponding name will be triggered through the name specified in notify
   - name: start httpd service
     service: enabled=true name=httpd state=started
  handlers:     #Tasks are defined in handlers. The tasks in handlers here use the service module
   - name: restart httpd    #The names of tasks in notify and handlers must be consistent
     service: name=httpd state=restarted
##Ansible does not execute the corresponding handler immediately after executing a task, but executes the handler after all ordinary tasks in the current play. This has the advantage that notify can be triggered multiple times, but only execute the corresponding handler once in the end, so as to avoid multiple restarts.

Note: prepare / opt / httpd in advance Conf file

2. Run playbook

ansible-playbook test1.yaml

#Supplementary parameters:
-k(–ask-pass): Used for interactive input ssh password
-K(-ask-become-pass): Used for interactive input sudo password
-u: Designated user

ansible-playbook test1.yaml --syntax-check    #Check that the syntax of the yaml file is correct
ansible-playbook test1.yaml --list-task       #Check tasks
ansible-playbook test1.yaml --list-hosts      #Check valid hosts
ansible-playbook test1.yaml --start-at-task='install httpd'     #Specify a task to run from

3. Define and reference variables

vim test2.yaml
---
- name: second play
  hosts: dbservers
  remote_user: root
  vars:                 #Define variables
   - groupname: mysql   #The format is key: value
   - username: nginx
  tasks:
   - name: create group
     group: name={{groupname}} system=yes gid=306    #Use {{key}} to reference the value of the variable
   - name: create user
     user: name={{username}} uid=306 group={{groupname}} 
   - name: copy file
     copy: content="{{ansible_default_ipv4}}" dest=/opt/vars.txt    #The facts variable information can be obtained in the setup module


ansible-playbook test2.yaml -e "username=nginx"     #Define variables on the command line

4. Specify the remote host sudo switch user

vim test3.yaml
---
- hosts: dbservers
  remote_user: zz
  become: yes	                 #The parameter after version 2.6, formerly sudo, means to switch the user's operation
  become_user: root              #Specify sudo user as root
 implement playbook When: ansible-playbook test3.yml -K <password>

5.when condition judgment

In Ansible, the only general condition judgment provided is the when instruction. When the value of the when instruction is true, the task will be executed; otherwise, the task will not be executed

when A common application scenario is to skip a host and do not execute tasks, or only qualified hosts execute tasks

vim test4.yaml
---
- hosts: all
  remote_user: root
  tasks:
   - name: shutdown host 
     command: /sbin/shutdown -r now
     when: ansible_default_ipv4.address == "192.168.19.77"      #The variable name in the when directive does not need to be manually added with {}
or 
     when: inventory_hostname == "<host name>"
	
ansible-playbook test4.yaml

6. Iteration

Ansible provides many kinds of loop structures, which are generally named with_items, which is equivalent to a loop loop.

vim test5.yaml
---
- name: play1
  hosts: dbservers
  gather_facts: false
  tasks: 
    - name: create directories
      file:
        path: "{{item}}"
        state: directory
      with_items:          #Equivalent to loop:
        - /tmp/test1
        - /tmp/test2
    - name: add users
      user: name={{item.name}} state=present groups={{item.groups}}
      with_items:
        - name: test1
          groups: wheel
        - name: test2
          groups: root
 or
      with_items:
        - {name:'test1', groups:'wheel'}
        - {name:'test2', groups:'root'}

ansible-playbook test5.yaml

4, Templates module

Jinja is a Python based template engine. Template class is an important component of Jinja. It can be regarded as a compiled template file, which is used to generate target text and pass Python variables to the template to replace the tags in the template.

1.Prepare one first .j2 Suffix template Template file, setting referenced variables
cp /etc/httpd/conf/httpd.conf /opt/httpd.conf.j2

vim /opt/httpd.conf.j2
Listen {{http_port}}				#Line 42, modified
ServerName {{server_name}}			#Line 95, modified
DocumentRoot "{{root_dir}}"          #Line 119, modify

2.Modify the host list file and use the host variable to define a variable with the same variable name but different values
vim /etc/ansible/hosts       
[webservers]
192.168.19.66 http_port=192.168.19.66:80 server_name=www.feng.com:80 root_dir=/etc/httpd/htdocs

[dbservers]
192.168.19.77 http_port=192.168.19.77:80 server_name=www.dian.com:80 root_dir=/etc/httpd/htdocs

3.to write playbook 
vim apache.yaml
---
- hosts: all
  remote_user: root
  vars:
    - package: httpd
    - service: httpd
  tasks:
    - name: install httpd package
      yum: name={{package}} state=latest
    - name: install configure file
      template: src=/opt/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf     #Use template template
      notify:
        - restart httpd
    - name: create root dir
	  file: path=/etc/httpd/htdocs state=directory
    - name: start httpd server
      service: name={{service}} enabled=true state=started
  handlers:
    - name: restart httpd
      service: name={{service}} state=restarted

ansible-playbook apache.yaml



Note: create / etc/httpd/htdocs and be mounted by the management machine at the same time.

5, tags module

You can define "tags" for one or some tasks in a playbook. When executing this playbook, you can run only the specified tasks by using the – tags option through the ansible playbook command.
playbook also provides a special tags for always. The function is that when the task of always is used, no matter which tag is executed, the tags with always defined will be executed.

vim webhosts.yaml
---
- hosts: webservers
  remote_user: root
  tasks:
    - name: Copy hosts file
      copy: src=/etc/hosts dest=/opt/hosts
      tags:
        - only     #Customizable
    - name: touch file
      file: path=/opt/testhost state=touch
	  tags:
	    - always    #Represents the code to always run

ansible-playbook webhosts.yaml --tags="only"
vim dbhosts.yaml
---
- hosts: dbservers
  remote_user: root
  tasks:
    - name: Copy hosts file
      copy: src=/etc/hosts dest=/opt/hosts
      tags:
        - only
    - name: touch file
      file: path=/opt/testhost state=touch
      tags:
	    - always

ansible-playbook dbhosts.yaml --tags="only"

Go to the two managed hosts to check the file creation

6, Roles module

Ansible in order to organize the Playbook hierarchically and structurally, Role used (roles), roles can automatically load variable files, tasks, handlers, etc. according to the hierarchical structure. In short, roles can easily include variables, files, tasks, modules and processors by placing them in separate directories. Roles are generally used in the scenario of building services based on hosts, but they can also be used in the scenario of building daemons Yes.

1. Interpretation of the contents in roles

files
Used to store files called by copy module or script module.

templates
It is used to store jinjia2 templates. The template module will automatically find jinjia2 template files in this directory.

tasks
This directory should contain a main YML file is used to define the task list of this role. This file can use include to contain other task files located in this directory.

handlers
This directory should contain a main YML file, which is used to define the actions to be performed when triggering conditions in this role.

vars
This directory should contain a main YML file, which is used to define the variables used in this role.

defaults
This directory should contain a main YML file, which is used to set default variables for the current character.

meta
This directory should contain a main YML file, which is used to define the special settings of this role and its dependencies.

2. Steps of using roles in Playbook

(1)Create to roles Named directory
mkdir /etc/ansible/roles/ -p    #yum will be installed by default

(2)Create global variable directory (optional)
mkdir /etc/ansible/group_vars/ -p
touch /etc/ansible/group_vars/all     #The file name is defined by itself. Pay attention when referencing

(3)stay roles Create a directory with each role name command in the directory, such as httpd,mysql
mkdir /etc/ansible/roles/httpd
mkdir /etc/ansible/roles/mysql

(4)Create in the directory of each role command files,handlers,tasks,templates,meta,defaults and vars Directory. Unused directories can be created as empty directories or not
mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,defaults,meta}
mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta}

(5)In each role handlers,tasks,meta,defaults,vars Create under directory main.yml File. You must not customize the file name
touch /etc/ansible/roles/httpd/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml

(6)modify site.yml File to call different roles for different hosts
vim /etc/ansible/site.yml
---
- hosts: webservers
  remote_user: root
  roles:
     - httpd
- hosts: dbservers
  remote_user: root
  roles:
     - mysql
	 
(7)function ansible-playbook
cd /etc/ansible
ansible-playbook site.yml


give an example:
mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,defaults,meta} -p
mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta} -p
mkdir /etc/ansible/roles/php/{files,templates,tasks,handlers,vars,defaults,meta} -p

touch /etc/ansible/roles/httpd/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/php/{defaults,vars,tasks,meta,handlers}/main.yml

3. Write httpd module

Write a simple tasks/main.yml
vim /etc/ansible/roles/httpd/tasks/main.yml
- name: install apache
  yum: name={{pkg}} state=latest
- name: start apache
  service: enabled=true name={{svc}} state=started
 
#Define variable: it can be defined in global variables or roles variables. Generally, it is defined in role variables
vim /etc/ansible/roles/httpd/vars/main.yml
pkg: httpd
svc: httpd

4. Write mysql module

vim /etc/ansible/roles/mysql/tasks/main.yml
- name: install mysql
  yum: name={{pkg}} state=latest
- name: start mysql
  service: enabled=true name={{svc}} state=started
  
vim /etc/ansible/roles/mysql/vars/main.yml
pkg:
  - mariadb
  - mariadb-server
svc: mariadb

5. Write php module

vim /etc/ansible/roles/php/tasks/main.yml
- name: install php
  yum: name={{pkg}} state=latest
- name: start php-fpm
  service: enabled=true name={{svc}} state=started

vim /etc/ansible/roles/php/vars/main.yml
pkg:
  - php
  - php-fpm
svc: php-fpm

6. Write roles examples

vim /etc/ansible/site.yml
---
- hosts: webservers
  remote_user: root
  roles:
   - httpd
   - mysql
   - php


cd /etc/ansible
ansible-playbook site.yml

Added by KFredje on Mon, 03 Jan 2022 01:48:58 +0200