Ansible是一种自动化运维工具,基于Python开发,主要用于自动化IT任务,如配置管理、应用程序部署、软件升级和系统管理等。它集合了众多运维工具(如puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。
Ansible的特性包括:
-
模块化:Ansible基于模块工作,可以调用特定的模块完成特定任务,支持自定义模块,可使用任何编程语言编写模块。
-
易于理解和维护:Ansible的配置是以纯文本格式书写的,可读性强,易于理解和维护。
-
基于SSH协议:Ansible使用SSH协议与远程主机通信,无需任何代理软件即可管理远程主机。
-
安全性:Ansible的安全性高,基于Python和SSH(默认已安装),无需代理,不依赖PKI(无需SSL)。
-
强大的功能:Ansible提供了丰富的功能和模块,可用于管理各种类型的系统和服务,支持主流操作系统,包括Linux、Unix和Windows。
此外,Ansible还提供了一系列用于云计算、虚拟化、网络设备和容器管理的模块,使其成为一个全面的自动化解决方案。通过使用Ansible,管理员可以在多个系统上协同工作,并简化常见任务的执行。
实验环境
系统 :Redhat 9.2
主机名 ip | 角色 |
---|---|
ansible-server 192.168.200.133 | 管理主机 |
host01 192.168.200.129 | 被管理主机 |
host02 192.168.200.130 | 被管理主机 |
更名,并关闭防火墙和selinux
#server
[root@admin ~]# hostnamectl hostname ansible-server
[root@admin ~]# bash
[root@ansible-server ~]# systemctl stop firewalld.service
[root@ansible-server ~]# systemctl disable firewalld.service
Removed "/etc/systemd/system/multi-user.target.wants/firewalld.service".
Removed "/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service".
[root@ansible-server ~]# setenforce 0
[root@ansible-server ~]# sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
#host01
[root@AI ~]# hostnamectl hostname host01
[root@AI ~]# bash
[root@host01 ~]# systemctl stop firewalld
[root@host01 ~]# systemctl disable firewalld
[root@host01 ~]# setenforce 0
setenforce: SELinux is disabled
[root@host01 ~]# sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
#host02
[root@host02 ~]# systemctl stop firewalld.service
[root@host02 ~]# systemctl disable firewalld.service
Removed "/etc/systemd/system/multi-user.target.wants/firewalld.service".
Removed "/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service".
[root@host02 ~]# setenforce 0
[root@host02 ~]# sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
1.管理节点修改 /etc/hosts文件实现本地解析
2.ssh密钥认证,并传送到被管理节点
3.验证ssh免密登录
[root@ansible-server ~]# vim /etc/hosts
........
192.168.200.129 host01 //添加这两行,此为被管理主机地址
192.168.200.130 host02
[root@ansible-server ~]# ssh-keygen //回车即可
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa
Your public key has been saved in /root/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:eLm/zpgULt9qDzMT+HE6vIjwFDvRPWs7EjZyEYoqKuc root@ansible-server
The key's randomart image is:
+---[RSA 3072]----+
| |
| . |
| . . . |
| . ...+ . |
| . o +.S . |
|o .+== X |
|o . ++.o/ |
|o .+ o.*o# |
|.oE o .oB=B. |
+----[SHA256]-----+
[root@ansible-server ~]#
[root@ansible-server ~]# for i in host01 host02
> do
> ssh-copy-id $i
> done //回车即可
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host 'host01 (192.168.200.129)' can't be established.
ED25519 key fingerprint is SHA256:AW6CbI38rOspHzJ9HwZlKrdMF7grkizUFrHF4loe1DU.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@host01's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'host01'"
and check to make sure that only the key(s) you wanted were added.
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host 'host02 (192.168.200.130)' can't be established.
ED25519 key fingerprint is SHA256:CH5kzY0f6wQEiX5BriG76RJrD0YAjo0BXuT6gmYRSnI.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@host02's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'host02'"
and check to make sure that only the key(s) you wanted were added.
[root@ansible-server ~]#
#验证登录
[root@ansible-server ~]# ssh host01
Web console: https://AI.localdomain:9090/ or https://192.168.200.129:9090/
Register this system with Red Hat Insights: insights-client --register
Create an account or view all your systems at https://red.ht/insights-dashboard
Last login: Tue May 7 18:14:48 2024 from 192.168.200.1
[root@host01 ~]# exit
注销
Connection to host01 closed.
[root@ansible-server ~]# ssh host02
Activate the web console with: systemctl enable --now cockpit.socket
Register this system with Red Hat Insights: insights-client --register
Create an account or view all your systems at https://red.ht/insights-dashboard
Last login: Tue May 7 18:14:41 2024 from 192.168.200.1
[root@host02 ~]# exit
注销
Connection to host02 closed.
[root@ansible-server ~]#
配置好仓库
[root@ansible-server ~]# mount /dev/sr0 /media/
mount: /media: WARNING: source write-protected, mounted read-only.
[root@ansible-server ~]#cd /etc/yum.repos.d/
[root@ansible-server yum.repos.d]# cat local.repo
[AppStream]
name=AppStream
baseurl=file:///media/AppStream
enabled=1
gpgcheck=0
[BaseOS]
name=BaseOS
baseurl=file:///media/BaseOS
enabled=1
gpgcheck=0
[root@ansible-server yum.repos.d]#
安装ansible
[root@ansible-server ~]# yum -y install ansible*
正在更新 Subscription Management 软件仓库。
无法读取客户身份
本系统尚未在权利服务器中注册。可使用 subscription-manager 进行注册。
上次元数据过期检查:0:15:37 前,执行于 2024年05月07日 星期二 18时35分10秒。
依赖关系解决。
===============================================================================================================================
过程省略 。 。 。 。 。 。
完毕!
[root@ansible-server ~]#
[root@ansible-server ~]# ansible --version
ansible [core 2.14.2]
config file = /etc/ansible/ansible.cfg
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3.11/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/bin/ansible
python version = 3.11.2 (main, Feb 16 2023, 00:00:00) [GCC 11.3.1 20221121 (Red Hat 11.3.1-4)] (/usr/bin/python3.11)
jinja version = 3.1.2
libyaml = True
[root@ansible-server ~]#
定义ansible主机清单
[root@ansible-server ~]# vim /etc/ansible/hosts
[webserver]
host01
host02
[root@ansible-server ~]# ansible webserver --list
hosts (2):
host01
host02
ansible-doc命令介绍:
ansible-doc #模块⽂档命令
常⽤选项:
-l #列出所有模块列表
-s #查看模块帮助信息
[root@ansible-server ~]# ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
ping:
data: # Data to return for the `ping' return value. If this parameter is set to `crash', the module will
# cause an exception.
[root@ansible-server ~]#
#用ping测试webserver组主机ssh连通性
[root@ansible-server ~]# ansible webserver -m ping
host01 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
host02 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
[root@ansible-server ~]#
Ansible命令返回值的颜⾊表示:
绿⾊:代表命令执⾏成功了,对远程节点不会造成改变
⻩⾊:代表命令执⾏成功了,对远程节点造成了改变
红⾊:代表你的命令执⾏失败或者是有异常,反正就是错误了
粉⾊:代表命令执⾏后发出的警告信息,给我们⼀些建议(可以忽略)
为host01和host02安装ansible
#host01
[root@host01 ~]# cd /etc/yum.repos.d/
[root@host01 yum.repos.d]# mount /dev/sr0 /media/
mount: /media: WARNING: source write-protected, mounted read-only.
[root@host01 yum.repos.d]# cat local.repo
[AppStream]
name=AppStream
baseurl=file:///media/AppStream
enabled=1
gpgcheck=0
[BaseOS]
name=BaseOS
baseurl=file:///media/BaseOS
enabled=1
gpgcheck=0
[root@host01 yum.repos.d]# cd
[root@host01 ~]# yum -y install ansible*
过程省略 。 。 。 。 。
#host02
[root@host02 ~]# mount /dev/sr0 /media/
mount: /media: WARNING: source write-protected, mounted read-only.
[root@host02 ~]# cd /etc/yum.repos.d/
[root@host02 yum.repos.d]# cat local.repo
[AppStream]
name=AppStream
baseurl=file:///media/AppStream
enabled=1
gpgcheck=0
[BaseOS]
name=BaseOS
baseurl=file:///media/BaseOS
enabled=1
gpgcheck=0
[root@host02 yum.repos.d]# cd
[root@host02 ~]# yum -y install ansible*
过程省略 。 。 。 。
安装完成后,在ansible-server端执⾏yum安装模块,推送脚本⽂件⾄远程,远程执⾏脚本⽂件
[root@ansible-server ~]# ansible webserver -m yum -a "name=httpd"
//回显为换黄色就代表成功
host02 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": true,
"msg": "",
"rc": 0,
"results": [
"Installed: apr-1.7.0-11.el9.x86_64",
"Installed: apr-util-1.6.1-20.el9.x86_64",
"Installed: apr-util-bdb-1.6.1-20.el9.x86_64",
"Installed: mod_http2-1.15.19-4.el9_2.4.x86_64",
"Installed: apr-util-openssl-1.6.1-20.el9.x86_64",
"Installed: mod_lua-2.4.53-11.el9_2.4.x86_64",
"Installed: httpd-2.4.53-11.el9_2.4.x86_64",
"Installed: httpd-core-2.4.53-11.el9_2.4.x86_64",
"Installed: httpd-filesystem-2.4.53-11.el9_2.4.noarch",
"Installed: redhat-logos-httpd-90.4-1.el9.noarch",
"Installed: httpd-tools-2.4.53-11.el9_2.4.x86_64"
]
}
host01 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"msg": "Nothing to do",
"rc": 0,
"results": []
}
[root@ansible-server ~]#
在ansible端启⽤httpd服务,并在被管理节点上进⾏查看httpd服务是否 安装及能否访问测试⻚
[root@ansible-server ~]# ansible webserver -m service -a "name=httpd state=started"
//回显为换黄色就代表成功
host02 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": true,
"name": "httpd",
"state": "started",
"status": {
"AccessSELinuxContext": "system_u:object_r:httpd_unit_file_t:s0",
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"After": "remote-fs.target tmp.mount system.slice -.mount systemd-tmpfiles-setup.service systemd-journald.socket nss-lookup.target httpd-init.service sysinit.target network.target basic.target",
"AllowIsolate": "no",
"AssertResult": "no",
"AssertTimestampMonotonic": "0",
内容过多省略 。 。 。 。 。 。 。
查看服务的状态回显文字为黄色,显示正在运行中
[root@ansible-server ~]# ansible webserver -m shell -a "systemctl status httpd"
host01 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; preset: disabled)
Drop-In: /usr/lib/systemd/system/httpd.service.d
└─php-fpm.conf
Active: active (running) since Tue 2024-05-07 19:18:57 CST; 2min 10s ago
Docs: man:httpd.service(8)
Main PID: 48049 (httpd)
Status: "Total requests: 0; Idle/Busy workers 100/0;Requests/sec: 0; Bytes served/sec: 0 B/sec"
Tasks: 213 (limit: 48630)
Memory: 45.8M
CPU: 213ms
CGroup: /system.slice/httpd.service
├─48049 /usr/sbin/httpd -DFOREGROUND
├─48068 /usr/sbin/httpd -DFOREGROUND
├─48069 /usr/sbin/httpd -DFOREGROUND
├─48070 /usr/sbin/httpd -DFOREGROUND
└─48071 /usr/sbin/httpd -DFOREGROUND
5月 07 19:18:04 host01 systemd[1]: Starting The Apache HTTP Server...
5月 07 19:18:33 host01 httpd[48049]: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using fe80::20c:29ff:feae:bdc8%ens160. Set the 'ServerName' directive globally to suppress this message
5月 07 19:18:57 host01 httpd[48049]: Server configured, listening on: port 80
5月 07 19:18:57 host01 systemd[1]: Started The Apache HTTP Server.
host02 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; preset: disabled)
Active: active (running) since Tue 2024-05-07 19:18:57 CST; 2min 10s ago
Docs: man:httpd.service(8)
Main PID: 34378 (httpd)
Status: "Total requests: 0; Idle/Busy workers 100/0;Requests/sec: 0; Bytes served/sec: 0 B/sec"
Tasks: 213 (limit: 10804)
Memory: 23.3M
CPU: 137ms
CGroup: /system.slice/httpd.service
├─34378 /usr/sbin/httpd -DFOREGROUND
├─34379 /usr/sbin/httpd -DFOREGROUND
├─34380 /usr/sbin/httpd -DFOREGROUND
├─34381 /usr/sbin/httpd -DFOREGROUND
└─34382 /usr/sbin/httpd -DFOREGROUND
5月 07 19:18:04 host02 systemd[1]: Starting The Apache HTTP Server...
5月 07 19:18:33 host02 httpd[34378]: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using fe80::20c:29ff:fe41:33e9%ens160. Set the 'ServerName' directive globally to suppress this message
5月 07 19:18:57 host02 systemd[1]: Started The Apache HTTP Server.
5月 07 19:18:57 host02 httpd[34378]: Server configured, listening on: port 80
[root@ansible-server ~]#
前面防火墙和selinux以及关闭了,直接浏览器访问测试即可,
如果没有关闭利用ansible使用shell模块关闭即可
停止Apache服务
[root@ansible-server ~]# ansible webserver -m service -a "name=httpd state=stopped"
host02 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
省略 。 。 。 。 。
#查看状态
[root@ansible-server ~]# ansible webserver -m shell -a "systemctl status httpd"
host02 | FAILED | rc=3 >>
○ httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; preset: disabled) //关闭状态
Active: inactive (dead)
Docs: man:httpd.service(8)non-zero return code
host01 | FAILED | rc=3 >>
○ httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; preset: disabled) //关闭状态
Drop-In: /usr/lib/systemd/system/httpd.service.d
└─php-fpm.conf
Active: inactive (dead)
Docs: man:httpd.service(8)
5月 08 14:12:09 host01 systemd[1]: httpd.service: Unit cannot be reloaded because it is inactive.non-zero return code
[root@ansible-server ~]#