ansible

Ansible: Write variable to local file


I have the following ansible playbook that writes the content of the variable "hello" as a message (I got this code from an example online). I tried modifying it so it would write this to a local file however I got an error. The modified code and error message are below:

original code (successful):

- hosts: all
  vars:
    hello: world
  tasks:
  - name: Ansible Basic Variable Example
    debug:
      msg: "{{ hello }}"

modified code (unsuccessful):

- hosts: all
  vars:
    hello: world
  tasks:
  - name: Ansible Basic Variable Example
  - local_action: copy content={{hello}} dest=~/ansible_logfile
    debug:
      msg: "{{ hello }}"

error message:

ERROR! no action detected in task. This often indicates a misspelled module name, or incorrect module path.

The error appears to have been in '/space/mathewLewis/towerCodeDeploy/playBooks/test.yml': line 5, column 5, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  tasks:
      - name: Ansible Basic Variable Example
    ^ here

I would like to know how to write a variable to a file correctly


Solution

  • It's a simple syntax error.
    A Task is an entry in the list of tasks, which in YAML is designated by a - (dash).
    Task names are optional in Ansible.
    Both copy and debug are modules, which are supposed to be a task's "action".
    What the error message is telling you is that the task with name: Ansible Basic Variable Example does not have an action, which is because your local_action is a separate task, indicated by a -.

    Fixing your example with appropriate names for the tasks:

      - name: Write variable to file
        local_action: copy content="{{hello}}" dest=~/ansible_logfile
    
      - name: Output the variable
        debug:
          msg: "{{ hello }}"