Contrary to all the other answers and comments, there are some downsides to using the script
module. Especially when you are running it on a remote(not localhost) host. Here is a snippet from the official ansible documentation:
It is usually preferable to write Ansible modules rather than pushing
scripts. Convert your script to an Ansible module for bonus points!
The ssh connection plugin will force pseudo-tty allocation via -tt
when scripts are executed. Pseudo-ttys do not have a stderr channel
and all stderr is sent to stdout. If you depend on separated stdout
and stderr result keys, please switch to a copy+command set of tasks
instead of using script.
If the path to the local script contains spaces, it needs to be
quoted.
This module is also supported for Windows targets.
For example, run this script using script
module for any host other than localhost and notice the stdout
and stderr
of the script.
#!/bin/bash
echo "Hello from the script"
nonoexistingcommand
echo "hello again"
You will get something like the below; notice the stdout
has all the stderr
merged.(ideally line 6: nonoexistingcommand: command not found
should be in stderr
) So, if you are searching for some substring in stdout in the script output. you may get incorrect results.:
ok: [192.168.122.83] => {
"script_out": {
"changed": true,
"failed": false,
"rc": 0,
"stderr": "Shared connection to 192.168.122.83 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.122.83 closed."
],
"stdout": "Hello from the script\r\n/home/ps/.ansible/tmp/ansible-tmp-1660578527.4335434-35162-230921807808160/my_script.sh: line 6: nonoexistingcommand: command not found\r\nhello again\r\n",
"stdout_lines": [
"Hello from the script",
"/home/ps/.ansible/tmp/ansible-tmp-1660578527.4335434-35162-230921807808160/my_script.sh: line 6: nonoexistingcommand: command not found",
"hello again"
]
}
}
The documentation does not encourage users to use the script module; consider converting your script into an ansible module; here is a simple post by me explaining how to convert your script into an ansible module.
Also, if you plan to use async/poll
with the script module, then it is not supported; check this.
Some other important reasons, but not limited to:
If you are writing your module in python, you can use tons of features provided by Ansible Module.
For example, you can set idempotency by setting the changed_when
variable within the module. (see comment by @DanOPT).
you can securely use sensitive variables inside the module and keep it secure by setting no_log.
for a particular variable. If you would not use the module, it will be your responsibility to keep the sensitive variable secure from logs and stdout. Example:
password=dict(type='str',
required=True,
no_log=True)