首页 文章

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

提问于
浏览
26

如何将已注册的变量保存到文件中?我从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?

4 回答

  • 57

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

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

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

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

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

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

    每个远程主机(并行)将运行一次本地操作 . 如果您希望每个主机具有唯一文件,请确保将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
    

相关问题