How to execute a remote script with Ansible

Published on
Table of contents

The issue is simple: I want to run a script, that is located on the server.

The solution is also simple: use the builtin command Ansible module.

Placing the script on the server

If your script is already provisioned, you can skip to the next section.

For example, you could obtain the script from a remote source.

In this case I am defining a task to get the installer from the official docker site:

- name: download docker installer
dest: /home/user/
mode: '+x'

Another way could be to copy/scp it from your local machine to your server.

Running the script

Now that the file is in place, you can run it with the command module.

Again, I am using the Docker installer as an example:

- name: install docker from script
command: sh /home/user/
creates: /usr/bin/docker

Notice the creates option, that helps Ansible’s idempotency.

Meaning that Ansible won’t run this command if /usr/bin/docker exists.