7

I have many Ansible playbooks that will get included in much larger playbooks. For example:

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

Is there a way pass in a hostname and run this as a standalone task from the command line, or do I need to create another playbook to run these two tasks by themselves?

5

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.

| improve this answer | |
  • The docs and forum posts do give the impression that running a small piece of a larger whole is the answer (as opposed to running individual, self-contained parts). – Pyzo Feb 8 '14 at 15:28
1

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.

| improve this answer | |
0

Sure, you should be able to do something like:

$ ansible-playbook foo.yml -i hosts -u user --limit host.example.com
| improve this answer | |
  • When I run the above playbook like this I get ERROR: hosts declaration is required – Pyzo Feb 5 '14 at 23:23
0

I ran into this problem as well.

I worked around the problem by creating a small runner playbook, which I then call with a paramater.

> tree
.
├── ansible.cfg
├── inventory
├── taskrunner.yml
├── tasks
└── hello.yml

> cat taskrunner.yml:
  ---
  - hosts: all
    tasks:
    - name: "Runner will try to run task: {{ task }}"
      include: "{{ task }}"

> cat tasks/hello
  - name: print hello
    shell: echo hello world

> ansible-playbook taskrunner.yml -e task=tasks/hello.yml
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.