Ansible - Save registered variable to file

2019-01-13 10:30发布

How would I save a registered Variable to a file? I took this from the tutorial:

- hosts: web_servers

  tasks:

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

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

How would I save foo_result variable to a file e.g. foo_result.log using ansible?

4条回答
Melony?
2楼-- · 2019-01-13 11:07

I am using Ansible 1.9.4 and this is what worked for me -

- local_action: copy content="{{ foo_result.stdout }}" dest="/path/to/destination/file"
查看更多
Explosion°爆炸
3楼-- · 2019-01-13 11:11
---
- 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
查看更多
Root(大扎)
4楼-- · 2019-01-13 11:14

A local action will run once for each remote host (in parallel). If you want a unique file per host, make sure to put the inventory_hostname as part of the file name.

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

If you instead want a single file with all host's information, one way is to have a serial task (don't want to append in parallel) and then append to the file with a module (lineinfile is capable, or could pipe with a shell command)

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

Alternatively, you can add a second play/role/task to the playbook which runs against only local host. Then access the variable from each of the hosts where the registration command ran inside a template Access Other Hosts Variables Docs Template Module Docs

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-13 11:19

You can use the copy module, with the parameter content=.

I gave the exact same answer here: Write variable to a file in Ansible

In your case, it looks like you want this variable written to a local logfile, so you could combine it with the local_action notation:

- local_action: copy content={{ foo_result }} dest=/path/to/destination/file
查看更多
登录 后发表回答