下面是一个使用Ansible的示例,将Linux命令的主机名和结果保存为字典格式:
创建一个名为command_result.yml
的文件,用于保存主机名和命令结果的字典。
---
command_results: {}
创建一个名为command_playbook.yml
的Playbook文件,用于执行命令并将结果保存到字典中。
---
- name: Execute command and save results
hosts: all
gather_facts: false
vars:
command: "hostname" # 要执行的命令
tasks:
- name: Execute command
command: "{{ command }}"
register: command_output
- name: Save command output to the dictionary
set_fact:
command_results: "{{ command_results | combine({inventory_hostname: command_output.stdout}) }}"
# 将当前主机名和命令输出合并为字典
- name: Save command results to a file
hosts: localhost
gather_facts: false
tasks:
- name: Create command result file
copy:
content: "{{ command_results }}"
dest: "{{ playbook_dir }}/command_result.yml"
运行Playbook文件,执行命令并将结果保存到字典中。
ansible-playbook command_playbook.yml
在运行后,command_result.yml
文件将包含每个主机的主机名和命令结果的字典。
---
command_results:
host1: "hostname1"
host2: "hostname2"
host3: "hostname3"
这样,你就可以使用Ansible执行命令,并将主机名和结果保存为字典格式。