Ansible automatic operation and maintenance tool - module and host list

Ansible automatic operation and maintenance tool - module and host list

 

 

 

 

 

                     1, Ansible overview

                     2, ansible deployment

                     3, ansible command line module

                     4, inventory host list

 

 

 

 

 

 

1, Ansible overview

Ansible is a configuration management and application deployment tool developed based on Python. It is also shining in the field of automatic management. It combines the advantages of many old operation and maintenance tools. Ansible can basically realize the functions that Pubbet and Saltstack can achieve.

Ansible can batch configure, deploy and manage thousands of hosts. For example, for one or more operations that need to be switched to each host before, using ansible only needs to complete the operations of all hosts on a fixed ansible control node.

Ansible works based on modules. It only provides a running framework. It does not have the ability to complete tasks. Ansible's modules actually perform operations. For example, the copy module is used to copy files to the remote host, and the service module is used to manage the start, stop and restart of services.

One of the distinctive features of Ansible is Agentless, that is, there is no Agent. Like ordinary commands, Ansible is not C/S software, and it only needs to be installed once on a host as a control node. Usually, it controls the remote host based on ssh connection, and Ansible or other additional services do not need to be installed on the remote host.

When the user inputs a command or playbooks at the server terminal, the playbook will be disassembled into play through the predetermined rules, and then organized into tasks that can be recognized by ansible, call modules and plug-ins, send the temporary file to the remote client through SSH according to the host list, execute and return the results, and automatically delete it after execution.

Another distinctive feature of Ansible is that most of its modules have idempotence. Idempotency means that multiple operations or multiple executions have the same impact on system resources. For example, execute the systemctl stop xxx command to stop the service. When it is found that the target service to be stopped is already stopped, it will do nothing. Therefore, the result of multiple stops is still stop and will not change the result. It is idempotent, while systemctl restart xxx is non power.

Many Ansible modules will first judge whether the target node wants to execute a task when executing. Therefore, you can safely and boldly let Ansible execute a task. Repeated execution of a task will not produce any side effects most of the time.

2, ansible deployment

---------- ansible Environment installation and deployment ----------
Management end: 192.168.30.17			ansible
 Managed end: 192.168.30.18
 Managed end: 192.168.30.19

//Management side installation ansible
yum install -y epel-release			//Install the epel source first
yum install -y ansible

//ansible directory structure
/etc/ansible/
├── ansible.cfg			        #The configuration file of ansible generally does not need to be modified
├── hosts				#ansible host list, which is used to store information about remote hosts to be managed
└── roles/				#Public role directory

//Configure host list
cd /etc/ansible
vim hosts       
[webservers]			#Configuration group name
192.168.30.18			#IP address or host name of the managed host contained in the group (the host name needs to modify the / etc/hosts file first)

[dbservers]
192.168.30.19

//Configure key pair authentication
ssh-keygen -t rsa		#Enter all the way and log in without secret
sshpass -p 'abc1234' ssh-copy-id root@192.168.30.18
sshpass -p 'abc1234' ssh-copy-id root@192.168.30.19

Example:

 

 

 

 

3, ansible command line module

--------- ansible Command line module ---------
Command format: ansible <Group name> -m <modular> -a <parameter list>

ansible-doc -l				#List all installed modules and press q to exit

1.command modular
//Executing commands on the remote host does not support shell features such as pipeline and redirection.
ansible-doc -s command		#-s lists the description information and operation actions of the specified module

ansible 192.168.30.18 -m command -a 'date'		#Specify ip execution date
ansible webservers -m command -a 'date'			#Specify group execution date
ansible dbservers -m command -a 'date'       
ansible all -m command -a 'date'				#All stands for all hosts
ansible all -a 'ls /'							#If the - m module is omitted, the command module is run by default

//Common parameters:
chdir: Enter the directory in advance before running the command on the remote host
creates: Judge whether the specified file exists. If so, do not perform the following operations
removes: Judge whether the specified file exists. If so, perform the following operations

ansible all -m command -a "chdir=/home  ls ./"

2.shell modular
//Executing commands on the remote host is equivalent to calling the shell process of the remote host, and then opening a sub shell under the shell to run commands (supporting functions such as pipe symbols)
ansible-doc -s shell

ansible dbservers -m shell -a 'echo 123456 | passwd --stdin test"'
ansible dbservers -m shell -a 'echo $(ifconfig ens33 | awk "NR==2 {print $2}") | cut -d " " -f2'
ansible dbservers -m shell -a 'echo $(ifconfig ens33 | awk "NR==2 {print \$2}")'

3.cron modular
//Define a task schedule on the remote host. There are two state s: present means add (can be omitted), and absent means remove.
ansible-doc -s cron				#Press q to exit

//Common parameters:
minute/hour/day/month/weekday: branch/Time/day/month/week
job: Task plan commands to execute
name: Name of the task schedule

ansible webservers -m cron -a 'minute="*/1" job="/bin/echo helloworld" name="test crontab"'
ansible webservers -a 'crontab -l'
ansible webservers -m cron -a 'name="test crontab" state=absent'	#Remove the planned task. If the planned task does not have a name, name=None

4.user modular
//User management module
ansible-doc -s user

//Common parameters:
name: User name, required parameter
state=present|absent: Create an account or delete an account, present Indicates creation, absent Indicates deletion
system=yes|no: Is it a system account
uid: user uid
group: User basic group
shell: Used by default shell
move_home=yse|no: If the set home directory already exists, do you want to move the existing home directory
password: The password of the user. It is recommended to use the encrypted string
comment: User's comment information
remove=yes|no: When state=absent Delete user's home directory

ansible dbservers -m user -a 'name="test01"'				#Create user test01
ansible dbservers -m command -a 'tail /etc/passwd'
ansible dbservers -m user -a 'name="test01" state=absent'	#Delete user test01

5.group modular
//User group management module
ansible-doc -s group

ansible dbservers -m group -a 'name=mysql gid=306 system=yes'	#Create mysql group
ansible dbservers -a 'tail /etc/group'
ansible dbservers -m user -a 'name=test01 uid=306 system=yes group=mysql'	#Add test01 user to mysql group
ansible dbservers -a 'tail /etc/passwd'
ansible dbservers -a 'id test01'    

6.copy modular
//Used to copy the specified host file to the remote host
ansible-doc -s copy

//Common parameters:
dest: Point out the target and location of the copied file, and use the absolute path. If it is the source directory, it means that the target directory is also the directory. If the target file already exists, the original content will be overwritten
src: Indicates the path of the source file. Relative path or absolute path can be used. Direct directory assignment is supported. If the source is a directory, the target is also a directory
mode: Indicates the permissions of the target file when copying 
owner: Indicates the owner of the target file when copying
group: Indicates the group to which the target file belongs when copying
content: Indicates that the content copied to the target host cannot be the same as src Use together

ansible dbservers -m copy -a 'src=/etc/fstab dest=/opt/fstab.bak owner=root mode=640'
ansible dbservers -a 'ls -l /opt'
ansible dbservers -a 'cat /opt/fstab.bak'

ansible dbservers -m copy -a 'content="helloworld" dest=/opt/hello.txt'  #Write helloworld to the / opt/hello.txt file
ansible dbservers -a 'cat /opt/hello.txt' 

7.file modular
//Set file properties
ansible-doc -s file

ansible dbservers -m file -a 'owner=test01 group=mysql mode=644 path=/opt/fstab.bak'	#Modify the file's primary group permissions, etc
ansible dbservers -m file -a 'path=/opt/fstab.link src=/opt/fstab.bak state=link'    #Set / opt/fstab.link to the link file of / opt/fstab.bak
ansible dbservers -m file -a "path=/opt/abc.txt state=touch"			#Create a file
ansible dbservers -m file -a "path=/opt/abc.txt state=absent"			#Delete a file

8.hostname modular
//Used to manage host names on remote hosts
ansible dbservers -m hostname -a "name=mysql01"

9.ping modular
//Detect connectivity of remote hosts
ansible all -m ping

10.yum modular
//Installing and uninstalling packages on remote hosts
ansible-doc -s yum

ansible webservers -m yum -a 'name=httpd'					#Installation services
ansible webservers -m yum -a 'name=httpd state=absent'		#Uninstall service

11.service/systemd modular
//Used to manage the running state of the management service on the remote host
ansible-doc -s service

//Common parameters:
name: Managed service name
state=started|stopped|restarted: Actions include startup, shutdown or restart
enabled=yes|no: Indicates whether to set the service to start automatically
runlevel: If set enabled To enable and disable automatic startup, you need to define which operation targets are automatically started

ansible webservers -a 'systemctl status httpd'			#View the running status of web server httpd
ansible webservers -m service -a 'enabled=true name=httpd state=started'			#service httpd start 

12.script modular
//Realize remote batch running of local shell scripts
ansible-doc -s script

vim test.sh
#!/bin/bash
echo "hello ansible from script" > /opt/script.txt

chmod +x test.sh
ansible webservers -m script -a 'test.sh'
ansible webservers -a 'cat /opt/script.txt'

13.setup modular
//The facts component is used to collect the managed node information, which can be obtained by using the setup module
ansible-doc -s setup

ansible webservers -m setup				#Get facts information of mysql group host
ansible dbservers -m setup -a 'filter=*ipv4'    #Filter can be used to filter the specified facts information

Example:

command module

 

 

 

shell module

 

cron module

 

user module

 

 

group module

 

copy module

 

 

 

file module

 

 

 

 

 

 

 

hostname module

 

ping module

yum module

 

 

 

 

service/systemd module

 

 

 

 

 

script module

 

 

setup module

 

4, inventory host list

--------- inventory Host list ---------
//Inventory supports grouping hosts. Multiple hosts can be defined in each group, and each host can be defined in any one or more host groups.

//If you are a host with a similar name, you can use a list to identify each host.
vim /etc/ansible/hosts
[webservers]
192.168.30.18:2222		#The remote connection port is defined after the colon. The default is port 22 of ssh
192.168.30.1[2:5]

[dbservers]
db-[a:f].example.org	#Support matching a~f


//Variables in inventory
Inventory Variable name	              meaning
ansible_host                  ansible When connecting nodes IP address
ansible_port                  The port number of the other party, ssh The default value is 22 when connecting
ansible_user                  The host name used when connecting to the other host. When not specified, execution is used ansible or ansible-playbook User of the command
ansible_password              The name of the user at the time of connection ssh Password, valid only without key pair authentication
ansible_ssh_private_key_file  Specify key authentication ssh Private key file at connection time
ansible_ssh_common_args       provide for ssh,sftp,scp Additional parameters for the command
ansible_become                Allow privilege escalation
ansible_become_method         Specify how permissions are elevated, for example, by using sudo/su/runas Other ways
ansible_become_user           Which user's permission is promoted to? The default is promoted to root
ansible_become_password       Password when promoted to the specified user rights

(1)Host variable
[webservers]
192.168.30.18 ansible_port=22 ansible_user=root ansible_password=abc1234

(2)Group variable
[webservers:vars]			#Represents a variable defined for all hosts in the webservers group
ansible_user=root
ansible_password=abc1234

[all:vars]					#Represents a variable defined for all hosts in all groups
ansible_port=22

(3)Group nesting
[nginx]
192.168.30.20
192.168.30.21
192.168.30.22

[apache]
192.168.30.3[0:3]

[webs:children]		#Indicates that the web host group contains all hosts in the nginx group and apache group
nginx
apache

 

Added by centenial on Fri, 29 Oct 2021 04:41:08 +0300