-1

I'm trying to execute shell script from ansible playbook and also trying to capture the output on the console.

When I run the playbook I always get the below error " "out.stdout_lines": "VARIABLE IS NOT DEFINED!""

How do I run the script and get the output on the console?

---
- name: Deploy book
  hosts: All_Servers
  become_user: test_user
  become: true
  tasks:
    - name: Print a message
      command: sh ../scripts/test.sh
      register: out
    - debug: var=out.stdout_lines
      tags:
      - tag1
cat ../scripts/test.sh
echo "Test"
Ronald
  • 207
  • 1
  • 7

1 Answers1

1

Regarding your question

... execute shell script from ansible-playbook and also trying to capture the output on the console ...

you need to have all tasks tagged which you like to run if using ansible-playbook --tags="<tags>".

... it may be useful to run only specific parts of it instead of running the entire playbook.

---
- name: Deploy book
  hosts: all
  become_user: "{{ ansible_user }}"
  become: true
  
  tasks:

    - name: Run script
      shell:
        cmd: "/home/{{ ansible_user }}/scripts/test.sh"
        warn: false
      changed_when: false
      register: result
      tags: test,run,script

    - name: Show result
      debug:
        msg: "{{ result.stdout_lines }}"
      when: not ansible_check_mode
      tags: test,show,result

If only the task Show result is tagged or run but not Run script, Ansible will try to show only the result which isn't there. Therefore the error message .stdout_lines": "VARIABLE IS NOT DEFINED!".

You can test it by running the above test with different tags to get different behavior.

By using a block with a tag, you have just tagged both tasks.

If you want to apply a tag to many, but not all, of the tasks in your play, use a block and define the tags at that level.

Regarding executing a shell script you may have a look into whats the difference between Ansible raw, shell and command or difference between shell and command in Ansible.

U880D
  • 8,601
  • 6
  • 24
  • 40