Ansible:将注册的变量保存到文件

Ansible:将注册的变量保存到文件,ansible,Ansible,如何使用Ansible将注册的变量保存到文件中 目标: 我想收集系统中所有PCI总线和设备的详细信息,并将结果保存在某个地方,例如使用lspci。理想情况下,我应该在本地机器中有命令结果,以便进一步分析。 将结果也保存在具有给定条件的某个位置。 我的剧本是这样的: tasks: - name: lspci Debian command: /usr/bin/lspci when: ansible_os_family == "Debian" register:

如何使用Ansible将注册的变量保存到文件中

目标:

我想收集系统中所有PCI总线和设备的详细信息,并将结果保存在某个地方,例如使用lspci。理想情况下,我应该在本地机器中有命令结果,以便进一步分析。 将结果也保存在具有给定条件的某个位置。 我的剧本是这样的:

tasks: - name: lspci Debian command: /usr/bin/lspci when: ansible_os_family == "Debian" register: lspcideb - name: lspci RedHat command: /usr/sbin/lspci when: ansible_os_family == "RedHat" register: lspciredhat - name: copy content local_action: copy content="{{ item }}" dest="/path/to/destination/file-{{ item }}-{{ ansible_date_time.date }}-{{ ansible_hostname }}.log" with_items: - lspcideb - aptlist - lspciredhat 我的问题:

如何保存多个变量并将标准输出传输到本地计算机

- name: copy content
  local_action: copy content="{{ vars[item] }}" dest="/path/to/destination/file-{{ item }}-{{ ansible_date_time.date }}-{{ ansible_hostname }}.log"
  with_items:
    - lspcideb
    - aptlist
    - lspciredhat
说明:

必须在Jinja2表达式中嵌入变量名以引用其值,否则就是传递字符串。因此:

with_items:
  - "{{ lspcideb }}"
  - "{{ aptlist }}"
  - "{{ lspciredhat }}"
这是Ansible中的普遍规则。出于同样的原因,您使用了{item}not item和{{foo_result}}not foo_result

但是您也使用{item}}作为文件名,这可能会造成混乱

因此,您可以使用{{vars[item]}引用变量值

另一种方法是定义字典:

- name: copy content
  local_action: copy content="{{ item.value }}" dest="/path/to/destination/file-{{ item.variable }}-{{ ansible_date_time.date }}-{{ ansible_hostname }}.log"
  with_items:
    - variable: lspcideb
      value: "{{ lspcideb }}"
    - variable: aptlist
      value: "{{ aptlist }}"
    - variable: lspciredhat 
      value: "{{ lspciredhat }}"

太棒了。另外还有优化代码。如果任务的结果成功,我如何保存?示例-我只想在ansible_os_family==Debian时保存lspcideb变量值?并且仅当ansible_os_family==RedHat时才保存lspciredhat值?您应该能够使用defaultomit筛选器:{{vars[item]| defaultomit}来实现您想要的。
- name: copy content
  local_action: copy content="{{ item.value }}" dest="/path/to/destination/file-{{ item.variable }}-{{ ansible_date_time.date }}-{{ ansible_hostname }}.log"
  with_items:
    - variable: lspcideb
      value: "{{ lspcideb }}"
    - variable: aptlist
      value: "{{ aptlist }}"
    - variable: lspciredhat 
      value: "{{ lspciredhat }}"