如何通过Ansible CLI/临时命令注册任务输出并提取指定键值?
关于Ansible任务输出注册与提取的解决方案
当然可以处理Ansible任务的输出啦!不过你现在用的是ad-hoc命令(直接在命令行执行的单条命令),和Playbook里的register用法略有不同,我给你两种实用的解决办法:
一、命令行直接提取并保存目标键值
Ansible本身没有专门的“注册输出”参数,但可以通过格式化输出+命令行工具来提取字典里的指定键,再保存到文件。
你的原命令返回的是字典结构,ios_command模块的返回结果通常包含stdout(命令输出的字符串列表)、stdout_lines(按行拆分的输出列表)等键。我们可以用以下步骤操作:
- 先让Ansible输出JSON格式的结果,方便解析:
ansible all -m ios_command -a "commands='show run'" -i Resources/Inventory/hosts -f json
- 用
jq工具(一款轻量JSON解析工具)提取目标键,并重定向到文件。比如要提取stdout里的第一个元素(对应show run的输出):
ansible all -m ios_command -a "commands='show run'" -i Resources/Inventory/hosts -f json | jq '.[].stdout[0]' > show_run_output.txt
如果你的环境没有jq,也可以用Python的JSON模块临时解析,比如:
ansible all -m ios_command -a "commands='show run'" -i Resources/Inventory/hosts -f json | python3 -c "import json,sys; data=json.load(sys.stdin); print('\n'.join([host['stdout'][0] for host in data.values()]))" > show_run_output.txt
二、用Playbook的register关键字实现更灵活的控制
如果你需要更复杂的逻辑(比如按主机分别保存输出、后续复用变量),推荐用Playbook配合register关键字,这也是Ansible官方更推荐的方式:
- 编写一个简单的Playbook(比如命名为
capture_show_run.yml):
- name: Capture and save 'show run' output hosts: all gather_facts: no tasks: - name: Execute 'show run' command on IOS devices ios_command: commands: 'show run' register: show_run_result # 这里就是注册输出到变量show_run_result - name: Save target value to file copy: content: "{{ show_run_result.stdout[0] }}" # 提取stdout列表的第一个元素 dest: "./show_run_{{ inventory_hostname }}.txt" # 按主机名生成不同的文件
- 运行这个Playbook:
ansible-playbook -i Resources/Inventory/hosts capture_show_run.yml
这样每个设备的show run输出会单独保存到对应的文件里,后续还能在其他任务里复用show_run_result变量。
补充说明
ios_command模块的返回结构:你可以先执行原命令加-v参数查看完整的返回字典,确认你需要提取的键名(比如如果是多条命令,stdout列表会对应每个命令的输出)。- 如果只是想快速查看简化输出,也可以用
-o参数(ansible all -m ios_command -a "commands='show run'" -i Resources/Inventory/hosts -o),但这种格式不太适合解析提取。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

