2026-ansible
Ansible 学习
学习文档地址
https://docs.ansible.com/projects/ansible/latest/
https://cn-ansibledoc.readthedocs.io/zh-cn/latest/#ansible2-9 中文版
1、环境安装
前提条件:
ansible 通过ssh协议管理远程机器,所以需要开启ssh协议端口
管理机: Python 2.7+ 或者 Python 3.5+、ssh协议
受管理机:
Python 2.7+ 或者 Python 3.5+、ssh协议、SFTP,如果SFTP无法使用,你可以在ansible.cfg中将其修改为 SCP
如果受管理机器开启了SELinux,你需要安装 libselinux-python,不然的话 copy/file/template等相关联的功能都无法使用
1.1 安装步骤
“为什么叫 9.2 而不是 2.16?”
因为:
ansible-core 的版本号仍在 2.x(如 2.16)
而 ansible 这个“发行版包”自 2022 年起独立编号,从 5.x → 6.x → 7.x → 8.x → 9.x
所以你使用 yum info ansible或者dnf info ansible的时候发现是 9.x 或者更高的版本,这就是上面版本命名的变化无需担心
yum install ansible 或者 dnf install ansible 即可
[root@iZj6cebm1no7852ykiv7tzZ ~]# ansible --version
ansible 2.9.27
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Nov 14 2023, 16:14:06) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
[root@iZj6cebm1no7852ykiv7tzZ ~]#
安装ansible 命令补全功能
Ansible 从 2.9 版本开始支持命令行补全功能,但需要安装 argcomplete 插件。 argcomplete 完全支持 bash, 部分功能支持 zsh tcsh。
$ sudo yum install epel-release
$ sudo yum install python-argcomplete
有 2 种方式配置 argcomplete 使 Ansible 支持 shell 命令补全: 全局模式 ( globally ) 或者单个命令 ( per command )。
全局模式需要 Bash的版本是 4.2
[root@iZj6cebm1no7852ykiv7tzZ ~]# bash -version
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
[root@iZj6cebm1no7852ykiv7tzZ ~]# sudo activate-global-python-argcomplete
Installing bash completion script /etc/bash_completion.d/python-argcomplete.sh
这条命令将生成 bash 补全文件到全局配置默认目录。 可以使用 --dest 指定位置。
如果 bash 的版本不是 4.2,那必须独立声明注册每个脚本。
$ eval $(register-python-argcomplete ansible)
$ eval $(register-python-argcomplete ansible-config)
$ eval $(register-python-argcomplete ansible-console)
$ eval $(register-python-argcomplete ansible-doc)
$ eval $(register-python-argcomplete ansible-galaxy)
$ eval $(register-python-argcomplete ansible-inventory)
$ eval $(register-python-argcomplete ansible-playbook)
$ eval $(register-python-argcomplete ansible-pull)
$ eval $(register-python-argcomplete ansible-vault)
如果希望永久有效,如上命令需要写入到环境变量文件,~/.profile or ~/.bash_profile .
2、配置Ansible
关于ansible的核心配置都在 ansible.cfg,其中大多数的默认配置能够满足大部分用户需求
ansible-config 命令行可以列出可用选项和变量信息
3、ansible 用户指南
https://cn-ansibledoc.readthedocs.io/zh-cn/latest/user_guide/intro_getting_started.html

浙公网安备 33010602011771号