Getting a message if register failed inside a task

13 views
Skip to first unread message

דודו דודו

unread,
Mar 6, 2020, 1:09:49 AM3/6/20
to Ansible Project
HI, 

I have a task that create a folder on HDFS storage. 
If the folder exists I wish to show a message



- hosts: gw
become: true
become_user: hdfs
tasks:
- name: create folder in HDFS
shell: hadoop dfs -mkdir /tmp/dudu
ignore_errors: yes
register: result
when: result is failed
fail:
msg: folder exists 

Vladimir Botka

unread,
Mar 6, 2020, 1:55:34 AM3/6/20
to דודו דודו, ansible...@googlegroups.com
It's not possible to use two modules (shell and fail) in one task. There are
couple of scenarios how to handle this case.

1) Show a message and fail (fatal)

tasks:
- name: create folder in HDFS
command: hadoop dfs -mkdir /tmp/dudu
ignore_errors: yes
register: result
- fail:
msg: folder exists
when: result is failed

2) Show a message and continue

tasks:
- name: create folder in HDFS
command: hadoop dfs -mkdir /tmp/dudu
ignore_errors: yes
register: result
- debug:
msg: folder exists
when: result is failed

3) Execute the command if the folder does not exist else skip the command,
show a message and continue. Optionally change "debug" to "fail".

tasks:
- name: create folder in HDFS
command:
cmd: hadoop dfs -mkdir /tmp/dudu
creates: /tmp/dudu
ignore_errors: yes
register: result
- debug:
msg: "{{ result.stdout }}"
when: not result.changed

Next options would be to use "block". See "Error Handling In Playbooks"
https://docs.ansible.com/ansible/latest/user_guide/playbooks_error_handling.html#error-handling-in-playbooks

As a sidenote, quoting from "shell – Execute shell commands on targets"
https://docs.ansible.com/ansible/latest/modules/shell_module.html#notes

"If you want to execute a command securely and predictably, it may be
better to use the command module instead. Best practices when writing
playbooks will follow the trend of using command unless the shell module is
explicitly required..."

quoting from "command – Execute commands on targets"
https://docs.ansible.com/ansible/latest/modules/command_module.html#notes

"If you want to run a command through the shell (say you are using <, >, |,
etc), you actually want the shell module instead. Parsing shell
metacharacters can lead to unexpected commands being executed if quoting is
not done correctly so it is more secure to use the command module when
possible."
--

HTH,

-vlado

דודו דודו

unread,
Mar 6, 2020, 6:47:09 AM3/6/20
to Ansible Project
Thank you for your answer.  So basically I need to run 2 tasks BUT

If I have a list of folders that needs to be created and i will use with_items  - As I know, the first task will run on all folders and the MSG task will only verify the register of the last folder. 

Basically what I'm askingת is there a way to run 2 tasks (one by one) on the same item and not running each task in parallel for all items  
Reply all
Reply to author
Forward
0 new messages