- 新版本的 Ansible 对目标主机的 Python 版本要求必须在 3.7 以上,Centos 7.9 系统的包管理工具只能安装 Python 3.6.8,要安装更高版本的 Python,必须使用源码编译的方式安装。
- Ansible-core 2.16.x 版本可以不用在目标机上安装 Python3,可以使用系统自带的 Python 2.x
1 pip install ansible-core==2.16.13
- Ansible 的
raw
module 模块和script
module 不依赖受管机的 Python 环境。 因此,从技术角度上讲,可以使用 Ansible 这两个模块 ( raw module 和 script module ) 编译安装 Python 环境。
配置环境
创建 ansible 项目目录以及 ansible.cfg 文件
1
2
3
4
5
6mkdir system_init && cd system_init
cat > ansible.cfg <<EOF
[defaults]
inventory = /etc/ansible/hosts.ini
EOF创建主机清单文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20cat > /etc/ansible/hosts.ini <<EOF
[centos]
172.31.100.181
172.31.100.182
[ubuntu]
172.31.100.183
172.31.100.184
[centos:vars]
ansible_user=root
[ubuntu:vars]
ansible_user=developer
[multi:children]
centos
ubuntu
EOF准备被控节点系统初始化需要的文件(Centos7.9)
- CentOS-Base.repo:被控节点需要安装 Python3,需要更改 YUM 仓库镜像源
- pip.conf: (可选)配置被控节点 pip 的加速地址
管理端创建 SSH 密钥
1
2
3
4
5
6
7
8
9
10
11# 生成 ssh 密钥
ssh-keygen -q -t rsa -N '' -f ~/.ssh/id_rsa <<<y
# 自动添加 known_hosts
echo "StrictHostKeyChecking no" >> /etc/ssh/ssh_config
# 传输公钥到目标主机
ssh-copy-id root@172.31.100.181
ssh-copy-id root@172.31.100.182
ssh-copy-id developer@172.31.100.183
ssh-copy-id developer@172.31.100.184被控节点安装 Python3
- 使用 yum 安装 Python3
1
2
3
4
5# 同步 CentOS-Base.repo 配置文件到目标主机
ansible centos -m synchronize -a "src=./CentOS-Base.repo dest=/etc/yum.repos.d/CentOS-Base.repo"
# 在目标主机执行安装命令
ansible centos -m raw -a "yum install -y python3"- 使用脚本编译安装 Python 3.12.4
1
2
3
4# 拷贝安装包到目标主机
ansible centos -m synchronize -a "src=./install_python3 dest=/usr/local/src/"
# 远程执行安装脚本
ansible centos -m script -a "chdir=/usr/local/src/install_python3 /root/centos_init/install_python3.sh"测试被控节点是否能正常管理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17ansible centos -m ping
172.31.100.181 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/local/bin/python3.12"
},
"changed": false,
"ping": "pong"
}
172.31.100.182 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/local/bin/python3.12"
},
"changed": false,
"ping": "pong"
}