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.