Ansible:将注册的变量保存到文件 [英] Ansible: Save registered variables to file

查看:196
本文介绍了Ansible:将注册的变量保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How could I save a registered variables to a file using Ansible?

目标:

  1. 我想收集有关系统中所有PCI总线和设备的详细信息,并将结果保存在某处(例如,使用lspci.理想情况下,我应该在本地计算机中拥有命令结果以进行进一步分析).
  2. 也将结果保存在给定条件的某个位置.

我的剧本看起来像这样:

My playbook looks like this:

 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

我的问题:

如何保存多个变量并将stdout传输到本地计算机?

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


说明:


Explanation:

您必须在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆