当前位置:网站首页>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】
List of articles
- Preface
- One 、Ansible summary
- Two 、 Deploy Ansible
- 3、 ... and 、Ansible Command module
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
- 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
- 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 .

Two 、 Deploy Ansible
| Server type | IP Address | Software to install |
|---|---|---|
| Ansible Management server | 192.168.109.138 | Ansible |
| 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

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

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]

2.4 Set interactive and secret free login
vim /etc/ssh/ssh_config
35 StrictHostKeyChecking no
systemctl restart sshd



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

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



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

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


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

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



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


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




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'


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'


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

3.7.2 Create soft link

3.7.3 create a file , And delete the file

3.8 hostname modular
Used to manage host names on remote hosts
ansible dbservers -m hostname -a 'name=testhost'


3.9 ping modular
ansible all -m ping

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

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


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

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


边栏推荐
- C语言中函数指针与指针函数
- 窗口可不是什么便宜的东西
- Monitoring cannot be started after Oracle modifies the computer name
- Analyse approfondie de kubebuilder
- What is Web3
- ACL2022 | 分解的元学习小样本命名实体识别
- DFS and BFS concepts and practices +acwing 842 arranged numbers (DFS) +acwing 844 Maze walking (BFS)
- Basic idea of counting and sorting
- Kivy tutorial of setting the size and background of the form (tutorial includes source code)
- Poor math students who once dropped out of school won the fields award this year
猜你喜欢

C语言中函数指针与指针函数

Pointer and array are input in function to realize reverse order output
![[hand torn STL] list](/img/aa/7060ab20b41936419041067cf9daed.jpg)
[hand torn STL] list

【实践出真理】import和require的引入方式真的和网上说的一样吗

Chapter 9 Yunji datacanvas company has been ranked top 3 in China's machine learning platform market

【Android Kotlin协程】利用CoroutineContext实现网络请求失败后重试逻辑

Ansible中的inventory主机清单(预祝你我有数不尽的鲜花和浪漫)

深入解析Kubebuilder

Kivy tutorial of setting the size and background of the form (tutorial includes source code)

JS also exports Excel
随机推荐
如何设计 API 接口,实现统一格式返回?
Flex layout and usage
Common Oracle SQL statements
A picture to understand! Why did the school teach you coding but still not
What if the win11 screenshot key cannot be used? Solution to the failure of win11 screenshot key
计数排序基础思路
namespace基础介绍
R语言主成分pca、因子分析、聚类对地区经济研究分析重庆市经济指标
Jetson nano配置pytorch深度学习环境//待完善
树与图的深度优先遍历模版原理
jvm是什么?jvm调优有哪些目的?
sscanf,sscanf_ S and its related usage "suggested collection"
If you ask me about R code debugging, I will tell you head, STR, help
九章云极DataCanvas公司摘获「第五届数字金融创新大赛」最高荣誉!
Introduction to the PureMVC series
01机器学习相关规定
Lecture 3 of "prime mover x cloud native positive sounding, cost reduction and efficiency enhancement lecture" - kubernetes cluster utilization improvement practice
This "advanced" technology design 15 years ago makes CPU shine in AI reasoning
【736. Lisp 语法解析】
[Yugong series] go teaching course 005 variables in July 2022