当前位置:网站首页>Ansible overview and module explanation (you just passed today, but yesterday came to your face)

Ansible overview and module explanation (you just passed today, but yesterday came to your face)

2022-07-07 04:57:00 Steve lu

Preface

The commonly used automatic chemical industry has :

  • ansible
  • saltstack
  • puppet

These three are automation tools , It can be used to improve the efficiency of operation and maintenance management , Among the three operation and maintenance tools, the mainstream is ansible and saltstack.ansible and saltstack The difference is that ansible No need to install client , It also became ansible A big advantage of ; and saltstack You need to install the client , You don't have to install it , Their applicable scenarios are also different ,ansible For small businesses , Applicable when managing fewer servers ,saltstack For medium and large enterprises , because ansible Cannot execute in parallel saltstack Can be executed in parallel . But these three operation and maintenance tools have no advantages or disadvantages , Only the applicable scenarios are different .

One 、Ansible summary

1.1 Ansible Introduce

Ansible It's based on Python Development of configuration management and application deployment tools , Now it's also playing a great role in the field of automation management . It integrates the advantages of many old operation and maintenance tools ,Pubbet and Saltstack Functions that can be realized ,Ansible Basically all can be achieved .

1.2 Ansible What can be done

Ansible Can batch To configure 、 Deploy 、 Manage thousands of hosts . For example, you need to switch to one or more operations performed on each host before , Use Ansible Just a fixed one Ansible Control node to complete all host operations .

Ansible yes Module based work Of , It just provides a framework to run , It doesn't have the ability to complete the task itself , The real thing to do is Ansible Module , such as copy Module is used to copy files to the remote host ,service Module is used to manage the start of the service 、 stop it 、 Restart, etc. .

1.3 Why choose Ansible

Ansible since 2012 Since its release , It didn't take long for it to become popular in the United States . Be quickly IT The reason why people accept it is largely due to Michael DeHaan In the U.S. IT The fame and influence of the circle . Then it gradually became popular in various countries . The author chose Ansible The main reasons are as follows :

  • Ansible Based solely on Python Development , and DevOps It is already a trend in China ,Python Gradually popularized , The threshold for O & M personnel to develop tools by themselves is gradually reduced , Thanks to this , Convenience is right Ansible Secondary development ;
  • Ansible Rich built-in modules , There are even functional modules specially developed for business platforms , near 600 Modules can completely meet the needs of daily functions ;
  • stay Ansible Under the concept of decentralization , A simple copy operation can complete the migration of the management configuration center ;
  • Agentless( No client ), The client does not need any configuration , It can be used after being configured by the management end , This is very attractive . In the 10 Chapter describes how to deploy the configuration Windows The host side of the system , You will feel deeply after using .
  • since Ansible After the release of , And then AWS、Google CloudPlatform、Microsoft Azure、Cisco、HP、VMware、Twitter Wait for big companies to accept and put into use .

1.4 Two characteristics

  1. agentless: There is no need to install additional client software , Just install on one host anaible You can pass ash Control remote host ansib1c Operations are performed through modules
  2. Idempotency ;ansible Many modules will judge whether the remote host has performed this task , If it has been executed and the operation has not changed , Will not implement the change results

1.5 Ansible framework

Ansible Between the management node and the remote host node SSH Protocol to communicate . So configuration Ansible When , Just guarantee from Ansible Management node through SSH The protocol can connect to the managed remote node . Be careful ,SSH Must be configured for public key authentication login mode , Not password authentication .

Ansible It can be managed at the same time Red Hat Systematic Linux、Debian Systematic Linux as well as Windows host .Ansible The working principle of is shown in the figure .

 Insert picture description here

Two 、 Deploy Ansible

Server type IP Address Software to install
Ansible Management server 192.168.109.138Ansible
Managed client 192.168.109.131------
Managed client 192.168.109.132------

2.1 install ansible service

[[email protected] ~]#yum install -y epel-release
[[email protected] ~]#yum install -y ansible

[[email protected] ~]# cd /etc/ansible/
[[email protected] ansible]# ls
ansible.cfg  hosts  roles
----------------------------------------------------------------
ansible.cfg		# ansible Configuration file for , Generally, there is no need to modify 
hosts			# ansible List of hosts , For storing information about remote hosts that need to be managed 
roles			#  Public role Directory 

 Insert picture description here

2.2 Configure host list

vim /etc/ansible/hosts				
[webservers]		# Configuration group name 
192.168.109.131		# The managed hosts included in the Group IP Address or host name ( The host name needs to be modified first /etc/hosts file )
[dbservers]
192.168.109.132

 Insert picture description here

2.3 Configure key pair validation

# Generate key pair ( Enter all the way )
ssh-keygen -t rsa		
# Import the opposite host 
ssh-copy-id [email protected]
ssh-copy-id [email protected]

 Insert picture description here

2.4 Set interactive and secret free login

vim /etc/ssh/ssh_config
35    StrictHostKeyChecking no

systemctl restart sshd

 Insert picture description here
 Insert picture description here
 Insert picture description here

3、 ... and 、Ansible Command module

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

ansible-doc -l			# Query all installed modules , Press q sign out 

 Insert picture description here

There are more than 3000 modules , We only need to learn common

3.1 command modular

Execute command on remote host , Pipes are not supported , Redirect etc. shell Characteristics of .

ansible-doc -s command					#-s  List the description information and operation actions of the specified module 

ansible 192.168.109.131 -m command -a 'ifconfig'	# Appoint ip Carry out orders 
ansible webservers -m command -a 'free'				# Specify the group to execute the command 
ansible dbservers -m command -a 'free'
ansible all -m command -a 'date'					#all On behalf of all  hosts  host 
ansible all -a 'date'								# If omitted  -m  modular , It means the default  command  modular 

### Commonly used parameters 
chdir: Enter the directory in advance before running the command on the remote host 
creates: Determine whether the specified file exists , If there is , Do not perform the following operations 
removes: Determine whether the specified file exists , If there is , Perform subsequent operations 

 Insert picture description here
 Insert picture description here
 Insert picture description here

3.1.1 Example :chdir

[[email protected] opt]# ansible dbservers -m command -a 'chdir=/opt ls ./'
192.168.109.132 | CHANGED | rc=0 >>
rh

 Insert picture description here

3.1.2 Example :creates

# Determine whether the specified file exists , If there is , Do not perform the following operations 
[[email protected] opt]# ansible dbservers -m command -a 'creates=/opt/123.txt echo helloworld >/opt/123.txt '
192.168.109.132 | CHANGED | rc=0 >>
helloworld >/opt/123.txt

# Switch 132 Machine check 
[[email protected] opt]# ls
123.txt  rh

 Insert picture description here
 Insert picture description here

3.1.3 Example :removes

# Determine whether the specified file exists , If there is , Perform subsequent operations 
[[email protected] opt]# ansible dbservers -m command -a 'removes=/opt/123.txt touch /opt/123.txt'
[WARNING]: Consider using the file module with state=touch rather than running 'touch'.  If you need to use command because file is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
192.168.109.132 | CHANGED | rc=0 >>

[[email protected] opt]# ansible dbservers -m command -a 'removes=/opt/123.txt rm -f /opt/123.txt'
[WARNING]: Consider using the file module with state=absent rather than running 'rm'.  If you need to use command because file is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
192.168.109.132 | CHANGED | rc=0 >>

[[email protected] opt]# ansible dbservers -m command -a 'removes=/opt/123.txt touch /opt/123.txt'
192.168.109.132 | SUCCESS | rc=0 >>
skipped, since /opt/123.txt does not exist

 Insert picture description here

3.2 shell modular

Execute command on remote host , Equivalent to calling the shell process , Then in the shell Open next child shell Run the command ( Support functions such as pipe symbols )

ansible-doc -s shell
# write in helloworld To 123.txt
[[email protected] opt]# ansible dbservers -m shell -a 'echo helloworld >/opt/123.txt '
192.168.109.132 | CHANGED | rc=0 >>
# Filter IP Address 
[[email protected] opt]# ansible dbservers -m shell -a 'ifconfig ens33|awk "NR==2 {print \$2}"'
192.168.109.132 | CHANGED | rc=0 >>
192.168.109.132

 Insert picture description here
 Insert picture description here
 Insert picture description here

3.3 cron modular

Define the task schedule on the remote host , There are two states (state):present Express addition ( It can be omitted ),absent Indicated removal .

ansible-doc -s cron					# View related instructions , Press q sign out 

 Common parameters :
minute/hour/day/month/weekday: branch / when / Japan / month  / Zhou 
job: The command to be executed in the task plan 
name : Name of the task plan 

# Every two months 10 Copy the system kernel log to /opt/
linux:10 10,22 10 */2 * /usr/bin/cp  /var/log/messages /opt
ansible:
[[email protected] opt]# ansible dbservers -m cron -a 'minute="10" hour="10,20" day="10" month="*/2" job="/usr/bin/cp /var/log/messages /opt" name="test crontab"'
192.168.109.132 | CHANGED => {
    
    "ansible_facts": {
    
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test crontab"
    ]
}
# Check out the task list 
[[email protected] opt]# ansible dbservers -a 'crontab -l'
192.168.109.132 | CHANGED | rc=0 >>
#Ansible: test crontab
10 10,20 10 */2 * /usr/bin/cp  /var/log/messages /opt
[[email protected] opt]# 
# Switch to 132 Upload and view the machine 
[[email protected] opt]# crontab -l
#Ansible: test crontab
10 10,20 10 */2 * /usr/bin/cp  /var/log/messages /opt

 Insert picture description here
 Insert picture description here

3.4 user modular

User management module

ansible-doc -s user

 Common parameters :
name : user name , Required parameters 
state=present|absent: Create account or delete account ,present Representation creation ,absent  Said to delete 
system=yes|no: Whether it is a system account 
uid:  user uid
group: User base group 
groups: Additional group 
shell: Default shell
move_home=yse|no: If the set home diary already exists , Whether to move the existing home diary 
password: User's password , It is recommended to use encrypted strings 
comment: User's comment information 
remove=yes|no: When state=absent when ,  Delete user's home directory 

ansible webservers -m user -a 'name="test001"'						# establish 
ansible webservers -m command -a 'tail -1 /etc/passwd'				# Check to confirm 
ansible webservers -m user -a 'name="test001" state=absent'			# Delete 
ansible webservers -m command -a 'tail -1 /etc/passwd'				# Check to confirm 

 Insert picture description here
 Insert picture description here
 Insert picture description here
 Insert picture description here

3.5 group modular

User group management module

ansible-doc -s group			# View related documents 

ansible dbservers -m group -a 'name=mysql gid=300 system=yes'
ansible dbservers -m command -a 'tail -1 /etc/group'
ansible dbservers -m user -a 'name="test002" uid=300 system=yes group=mysql'
ansible dbservers -m command -a 'tail -2 /etc/passwd'
ansible dbservers -a 'id test002'

 Insert picture description here
 Insert picture description here

3.6 copy modular

Used to copy the specified host file to the remote host

ansible-doc -s copy				# View related documents 

## Common parameters 
dest: Point out the date mark and location of the copied document , Using absolute paths , If it is the source directory , The target is also a directory , If the target file already exists, the original content will be overwritten 
src: Indicates the path to the source file , You can use relative or absolute paths , Direct directory assignment is supported , If the source is a directory, the target is also a directory 
mode: When indicating replication , Permissions of the target file 
owner: When indicating replication , Owner of the target file 
group: When indicating replication , The group to which the target file belongs 
content: Indicate what is copied to the target host , Cannot be associated with src Use it together 

## Test creating files and modifying permissions 
ansible dbservers -a 'mkdir /test'
ansible dbservers -m copy -a 'src=/etc/passwd dest=/test/passwd.bak owner=root mode=640'
ansible dbservers -a 'ls -l /test'

## Test create file and write content 
ansible dbservers -m copy -a 'content="this is test txt" dest=/test/test.txt'
ansible dbservers -a 'ls -l /test'
ansible dbservers -a 'cat /test/test.txt'

 Insert picture description here
 Insert picture description here

3.7 file modular

Set file properties

ansible-doc -s file

# Modify the permissions of the main group of the file 
ansible dbservers -m file -a 'owner=zhangsan group=mysql mode=777 path=/opt/123.txt'	
ansible dbservers -a 'ls -l /opt'

## Set up /opt/123.txt.bak  by  /opt/123.txt  Link file for 
ansible dbservers -m file -a 'path=/opt/123.txt.link src=/opt/123.txt state=link'

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 

3.7.1 Modify owner, group and permission

 Insert picture description here

3.7.2 Create soft link

 Insert picture description here

3.7.3 create a file , And delete the file

 Insert picture description here

3.8 hostname modular

Used to manage host names on remote hosts

ansible dbservers -m hostname -a 'name=testhost'

 Insert picture description here
 Insert picture description here

3.9 ping modular

ansible all -m ping 

 Insert picture description here

3.10 yum modular

Install and uninstall the software package on the remote host

ansible-doc -s yum

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

 Insert picture description here

3.11 service/systemd modular

Used to manage the running state of the 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 you set enabled Start and start automatically , Then you need to define the running targets under which to start automatically .

ansible webservers -m service -a 'name=httpd enabled=true state=started'		# Install the service and set it to start automatically 
systemctl is-enabled  httpd.service			# The controlled end checks whether it is set to start automatically 

 Insert picture description here
 Insert picture description here

3.12 script modular

Realize remote batch operation of local shell Script

ansible-doc -s script

vim test.sh						# Write a script 
#!/bin/bash
echo "hello ansible from script" > /opt/script.txt		# stay script.txt Write the specified content in 

chmod +x test.sh 										# To give permission 
ansible dbservers -m script -a 'test.sh'				# Realize remote running of local scripts 
ansible dbservers -a 'cat /opt/script.txt'				# View the generated document content 

 Insert picture description here

3.13 setup modular

facts Component is used to collect information of managed nodes , Use setup The module can get this information

ansible-doc -s setup

ansible webservers -m setup							# obtain webservers Group host's facts Information 
ansible webservers -m setup -a 'filter=*ipv4'		# Use filter You can filter the specified facts Information 

 Insert picture description here
 Insert picture description here

原网站

版权声明
本文为[Steve lu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207062235582244.html

随机推荐