Ansible - 将注册变量保存到文件

问题描述 投票:32回答:4

如何将已注册的变量保存到文件中?我从tutorial拿走了这个:

- hosts: web_servers

  tasks:

     - shell: /usr/bin/foo
       register: foo_result
       ignore_errors: True

     - shell: /usr/bin/bar
       when: foo_result.rc == 5

如何将foo_result变量保存到文件中,例如foo_result.log使用ansible?

ansible ansible-playbook
4个回答
63
投票

您可以使用copy模块,参数content=

我在这里给出了完全相同的答案:Write variable to a file in Ansible

在您的情况下,看起来您希望将此变量写入本地日志文件,因此您可以将其与local_action表示法结合使用:

- local_action: copy content={{ foo_result }} dest=/path/to/destination/file

10
投票

我正在使用Ansible 1.9.4,这对我有用 -

- local_action: copy content="{{ foo_result.stdout }}" dest="/path/to/destination/file"

5
投票

每个远程主机(并行)将运行一次本地操作。如果您希望每个主机具有唯一文件,请确保将inventory_hostname作为文件名的一部分。

- local_action: copy content={{ foo_result }} dest=/path/to/destination/{{ inventory_hostname }}file

如果你想要一个包含所有主机信息的单个文件,一种方法就是拥有一个串行任务(不想并行追加),然后用一个模块附加到该文件(lineinfile有能力,或者可以用shell管道)命令)

- hosts: web_servers
  serial: 1
  tasks:
  - local_action: lineinfile line={{ foo_result }} path=/path/to/destination/file

或者,您可以向仅针对本地主机运行的剧本添加第二个播放/角色/任务。然后从模板中运行注册命令的每个主机访问变量Access Other Hosts Variables Docs Template Module Docs


1
投票
---
- hosts: all
  tasks:
  - name: Gather Version
    debug:
     msg: "The server Operating system is {{ ansible_distribution }} {{ ansible_distribution_major_version }}"
  - name: Write  Version
    local_action: shell echo "This is  {{ ansible_distribution }} {{ ansible_distribution_major_version }}" >> /tmp/output
© www.soinside.com 2019 - 2024. All rights reserved.