Run included ansible task as standalone task

There are two requirements to achieve this:-

  1. the host you're trying to target must be in an inventory file
  2. you need to tag the tasks in the role you want to run

    - name: Add user me
      user: name=me comment="Me" uid=9999 groups=somegroup
      tags: this_role
    - name: Add my ssh public key
      authorized_key: user=me key="{{ lookup('file', 'id_rsa.pub') }}"
      tags: this_role
    

Then you can:-

ansible-playbook foo.yml -i hosts -t this_role --limit host.example.com

Not that this is still running the playbook that contains the complete play, but it's limiting the tasks that run to just those that match the tag. The remaining tasks will be skipped.


Both user and authorized_key are modules. So you can call these with ansible -m from any script

ansible all -i host.example.com, -m user -a 'name=me comment="Me" uid=9999 groups=somegroup'
ansible all -i host.example.com, -m authorized_key -a "user=me key=\"{{ lookup('file', 'id_rsa.pub') }}\""

Note the trailing comma after the hostname.


Another approach would be to use include or include_tasks as in

ansible all -i host.example.com, -m include_tasks -a /path/to/some/taskfile.yml

Although include might become deprecated in the future (in favour of include_tasks or include_role)

Note

  • ...
  • This module will still be supported for some time but we are looking at deprecating it in the near future.