且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-16 14:20:01

- 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 }}"