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

Max*_*fer 38 ansible ansible-playbook

如何将已注册的变量保存到文件中?我从教程中得到了这个:

- hosts: web_servers

  tasks:

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

     - shell: /usr/bin/bar
       when: foo_result.rc == 5
Run Code Online (Sandbox Code Playgroud)

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

Ram*_*nte 72

您可以使用copy带参数的模块content=.

我在这里给出了完全相同的答案:将变量写入Ansible中的文件

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

- local_action: copy content={{ foo_result }} dest=/path/to/destination/file
Run Code Online (Sandbox Code Playgroud)

  • 从 Ansible 2.10 开始,“ansible.builtin.copy”的文档表示:_如果您需要在复制的文件中进行变量插值,请使用“ansible.builtin.template”模块。在 `content` 字段中使用变量将导致不可预测的输出。更多详细信息请参阅 https://github.com/ansible/ansible/issues/50580 以及 https://github.com/ansible/ansible 的解释/问题/34595#issuecomment-356091161 (2认同)
  • 建议使用模板的答案的编辑很差,因为它没有提供如何使用模板来解决原始问题的示例 (2认同)

小智 12

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

- local_action: copy content="{{ foo_result.stdout }}" dest="/path/to/destination/file"
Run Code Online (Sandbox Code Playgroud)


bot*_*aio 9

实现这一目标的更易读的方式(不是单行 ansible 任务的粉丝)

- local_action: 
    module: copy 
    content: "{{ foo_result }}"
    dest: /path/to/destination/file
Run Code Online (Sandbox Code Playgroud)


Cha*_*try 7

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

- local_action: copy content={{ foo_result }} dest=/path/to/destination/{{ inventory_hostname }}file
Run Code Online (Sandbox Code Playgroud)

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

- hosts: web_servers
  serial: 1
  tasks:
  - local_action: lineinfile line={{ foo_result }} path=/path/to/destination/file
Run Code Online (Sandbox Code Playgroud)

或者,您可以向仅针对本地主机运行的剧本添加第二个播放/角色/任务.然后从模板内运行注册命令的每个主机访问变量访问其他主机变量文档 模板模块文档