Ansible:将注册的变量保存到文件 [英] Ansible: Save registered variables to file
问题描述
如何使用 Ansible 将注册的变量保存到文件中?
How could I save a registered variables to a file using 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
但只保存item_name
在那里保存 1 个变量的好问答 - Ansible - 将注册的变量保存到文件.
Good Q&A with saving 1 variable there - Ansible - Save registered variable to file.
- local_action: copy content={{ foo_result }} dest=/path/to/destination/file
我的问题:
如何保存多个变量并将标准输出传输到本地机器?
How can I save multiple variables and transfer stdout to my local machine?
推荐答案
- 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 表达式中嵌入变量名称以引用它们的值,否则您将传递字符串.所以:
You must embed variable names in Jinja2 expressions to refer to their values, otherwise you are passing strings. So:
with_items:
- "{{ lspcideb }}"
- "{{ aptlist }}"
- "{{ lspciredhat }}"
这是 Ansible 的通用规则.出于同样的原因,您使用 {{ item }}
而不是 item
,而 {{ foo_result }}
而不是 foo_result
.
It's a universal rule in Ansible. For the same reason you used {{ item }}
not item
, and {{ foo_result }}
not foo_result
.
但是您还使用 {{ item }}
作为文件名,这可能会造成混乱.
But you use {{ item }}
also for the file name and this will likely cause a mess.
所以你可以用:{{ vars[item] }}
来引用变量值.
So you can refer to the variable value with: {{ vars[item] }}
.
另一种方法是定义字典:
Another method would be to define a dictionary:
- 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:将注册的变量保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!