Ansible 是业界主流的自动化运维工具,默认输出格式为人类可读的文本。但在与 CI/CD 系统、监控平台或自动化脚本集成时,JSON 格式的结构化输出更便于程序解析。本文以 CentOS 7 环境为例,详细介绍 Ansible 2.4.6 的离线安装方法及 JSON 输出配置。
核心内容包括:
软件包安装:
ansible-2.4.6.0-1.el7.ans.noarch.rpmyum localinstall 完成本地安装ansible --version 验证安装结果JSON 输出配置:
ansible-doc -t callback -l | grep json/etc/ansible/ansible.cfg 配置文件:
inistdout_callback = json
callback_whitelist = json, yaml
bin_ansible_callbacks = True
可选配置:指定 Python 解释器路径(interpreter_python)
测试验证:
本文适用于需要通过 Ansible 与外部系统(如 Jenkins、ELK、Prometheus)进行数据对接的运维开发人员。
text仓库:https://releases.ansible.com/ansible/rpm/release/epel-7-x86_64/ 下载地址:https://releases.ansible.com/ansible/rpm/release/epel-7-x86_64/ansible-2.4.6.0-1.el7.ans.noarch.rpm
shellwget https://releases.ansible.com/ansible/rpm/release/epel-7-x86_64/ansible-2.4.6.0-1.el7.ans.noarch.rpm
# yum本地安装
yum localinstall ansible-2.4.6.0-1.el7.ans.noarch.rpm -y
# 验证安装(ok)
[root@localhost local]# ansible --version
ansible 2.4.6.0
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 16 2020, 22:23:17) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
# 验证功能(ok)
[root@localhost local]# ansible 127.0.0.1 -m ping
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit
localhost does not match 'all'
127.0.0.1 | SUCCESS => {
"changed": false,
"failed": false,
"ping": "pong"
}
shell# 展示可用的回调插件列表
ansible-doc -t callback -l|grep json
# 检查配置文件所在路径
ansible --version|grep 'config file'
# 编辑配置文件
vi /etc/ansible/ansible.cfg
# 新增配置(如果有则改,无则加)
stdout_callback = json
#### 确保 stdout_callback 在 whitelist 中
callback_whitelist = json, yaml
bin_ansible_callbacks = True
# 新增配置(非必须)
interpreter_python = /usr/local/python3/bin/python3
shell[root@localhost ~]# ansible -m ping 127.0.0.1 { "custom_stats": {}, "global_custom_stats": {}, "plays": [ { "play": { "duration": { "end": "2023-02-11T07:21:40.321582Z", "start": "2023-02-11T07:21:40.244100Z" }, "id": "000c29bc-d84f-3995-b8bc-000000000007", "name": "Ansible Ad-Hoc" }, "tasks": [ { "hosts": { "127.0.0.1": { "action": "ping", "changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", "unreachable": true } }, "task": { "duration": { "end": "2023-02-11T07:21:40.321582Z", "start": "2023-02-11T07:21:40.271688Z" }, "id": "000c29bc-d84f-3995-b8bc-000000000009", "name": "ping" } } ] } ], "stats": { "127.0.0.1": { "changed": 0, "failures": 0, "ignored": 0, "ok": 0, "rescued": 0, "skipped": 0, "unreachable": 1 } } }


本文作者:Odboy
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC 4.0 BY-SA 许可协议。转载请注明出处!