Save Output to Local File with Ansible

From Knowledge Center
Jump to: navigation, search

Inventory

This playbook demonstrates how you can redirect shell output to a local file

inventory.ini

[local]
localhost

The Script

/tmp/foo

#!/usr/bin/env bash
echo "foo"
echo "bar"

Apply executable permissions:

$ chmod +x /tmp/foo

Playbook

debug.yml

---
- hosts: local
  tasks:
    - shell: /tmp/foo
      register: foo_result
      ignore_errors: True
    - local_action: copy content={{ foo_result.stdout }} dest=file

Running the Playbook

$ ansible-playbook -i inventory.ini debug.yml

ansible-playbook -i local_hosts local.yml

PLAY [local] ************************************************************************************************************************************************************************

TASK [shell] ************************************************************************************************************************************************************************
changed: [localhost]

TASK [copy] *************************************************************************************************************************************************************************
changed: [localhost -> localhost]

PLAY RECAP **************************************************************************************************************************************************************************
localhost                  : ok=2    changed=2    unreachable=0    failed=0

View the local file:

foo
bar