Local tasks in Ansible playbook

Sometimes while running ansible playbooks, I require a certain role to run some task locally before I can hand its output to be passed to a remote task. This may include processing some files in a certain manner before deployment. I tend to do these tasks manually if I remember to do it! I have lost hours debugging a failed playbook error only to realise afterwards I forgot to run these local preprocessing tasks first.

An ideal scenario would be to have roles that can execute commands locally.

In Ansible it is possible to specify a task to be run locally only. There are two ways of doing this: using the delegate_to or the local_action keyword.

The delegate_to keyword changes or specifies the host on which to run the task. If we set this to localhost, it will only run locally. No other config changes are required.

For example, to rebuild all the posts in my jekyll blog:

1
2
3
4
5
---
- name: Publish Posts
  run_once: true
  delegate_to: 127.0.0.1
  command: chdir= bundle exec jekyll build --config _config.yml

We can condense the above into a one-liner using local_action:

1
2
3
4
---
- name: Publish Posts
  run_once: true
  local_action: command chdir= bundle exec jekyll build --config _config.yml

The run_once ensures that the role is run only once.

More information on Delegation can be found on the Ansible Documentation website.

Happy Hacking!