Ansbile
版本
- ansible-core 2.17 - 控制节点python版本3.10-3.12, 目标节点python版本3.7-3.12
- ansible-core 2.11 - 控制节点python版本2.7, 3.5-3.9, 目标节点python版本2.6-2.7, 3.5-3.9
- 更多见Ansible版本支持矩阵和对应Python版本
支持centos 7, python2.7的最后一个ansible
python3 -m pip install --user ansible==9.8.0 \
--index-url=https://mirrors.aliyun.com/pypi/simple -v安装
准备工作
规划控制节点和目标节点。将在控制节点上安装ansible,目标节点只要有兼容的python版本即可。
在控制节点和目标节点(可选)的/etc/hosts配置文件中配置所有节点的ip地址和主机名。
在控制节点和目标节点上创建ansible用户,确保各节点上ansible用户具有sudo权限:
useradd ansible
# ubuntu
useradd -m -s /bin/bash ansible
passwd ansible
echo "ansible ALL = (root) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/ansible配置控制节点到各个目标节点的SSH无密访问。
安装ansible
下面在控制节点上安装ansible。
方法1: 使用pipx安装
在控制节点上切换到ansible用户,将只为ansible用户安装ansible。
su - ansible为当前ansible用户安装pip:
python3 -m ensurepip --upgrade --user安装pipx:
python3 -m pip install --user pipx --index-url=https://mirrors.aliyun.com/pypi/simple注意上面的命令安装pipx被安装在了~/.local/bin下。
使用pipx安装ansible:
pipx install --include-deps ansible -vvv --index-url=https://mirrors.aliyun.com/pypi/simplepipx安装的ansible是会在~/.local下,并且有独立的虚拟环境:
ls ~/.local/share/pipx/venvs/ansible/
bin include lib lib64 pipx_metadata.json pyvenv.cfg方法2: 使用pip安装
su - ansible
python3 -m ensurepip --upgrade --user
python3 -m pip install --user ansible \
--index-url=https://mirrors.aliyun.com/pypi/simple验证安装
在控制节点上编写资产文件/etc/ansible/hosts,文件的内容是所有目标节点的主机名:
sudo mkdir /etc/ansible
vi /etc/ansible/hosts[all]
targetnode1_hostname
targetnode2_hostname使用ping模块测试到目标节点的连通性:
ansible all -m ping使用command模块执行远程命令:
ansible all -m command -a "date"Module defaults
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_module_defaults.html
如果经常用相同的参数调用同一个模块,使用 module_defaults 关键字为该特定模块定义默认参数。
例如:
- hosts: localhost
module_defaults:
ansible.builtin.file:
owner: root
group: root
mode: 0755
tasks:
- name: Create file1
ansible.builtin.file:
state: touch
path: /tmp/file1
- name: Create file2
ansible.builtin.file:
state: touch
path: /tmp/file2
- name: Create file3
ansible.builtin.file:
state: touch
path: /tmp/file3module_defaults 可以在play、block和task层级中使用。在任务中明确指定的任何模块参数都会覆盖该模块参数已设置的默认值。
- block:
- name: Print a message
ansible.builtin.debug:
msg: "Different message"
module_defaults:
ansible.builtin.debug:
msg: "Default message"可以通过指定一个空字典来移除之前为模块设置的所有默认值。
- name: Create file1
ansible.builtin.file:
state: touch
path: /tmp/file1
module_defaults:
file: {}注意
在play层级设置的任何模块默认值(以及使用include_role或import_role时在block/task 层级设置的默认值)都会应用到所使用的任何role上,这可能会导致role出现意外的行为。