Ansible: Ad-Hoc Shell Module

I shared a tip on handling missing files in an Ansible playbook some time ago. I have now tried to do the same with ad hoc command execution. Here is how you can use extra module arguments.

As a quick reminder, you could use the shell module arguments "creates" and "removes" as an alternative module condition. While Ansible resolves the "when" clauses before the task execution on the controller side, shell arguments are resolved as a part of the module execution and produce a different outcome.

- name: Skip missing commands
  shell: 
    cmd: |
      /opt/app/cli/some-command 
    removes: /opt/app/cli  

Skips Command Execution if /opt/app/cli is missing

By common sense, running the shell module with the same arguments as the ad hoc command will produce the same results. Unfortunately, that's not the case. In the example below, I'm trying to get the list of files if the /tmp folder is present (Of course it is.)

~💲 docker run -it alpine/ansible bash 
/#️⃣ ansible localhost -m shell -a 'cmd="ls -la" removes="/tmp"' 

Conditional Execution.

The Ansible executes the command, but the result is empty. I have tried to change the order of the parameters and swap double and single brackets. The shell module in ad-hoc does not recognize the cmd argument at all.

The only working combination is to pass free-form shell commands accompanied by the other module arguments. The screenshot below depicts variations of the shell module execution results.

Ansible Shell Module Ignores the CMD argument in the Ad-Hoc Mode.

What we learned today confirms that some modules demonstrate a different behavior while running as a playbook task and the command line module, and some of them can't be executed from the command line at all.