How can I run an ansible role locally?

Viewed 1392

I want to build a docker image locally and deploy it so it can then be pulled on the remote server I'm deploying to. To do this I first need to check out code from git to be built.

I have an existing role which installs git, sets up keys for reading from our repo etc. I want to run this role locally to check out the code I care about.

I looked at local action, delegate_to, etc but haven't figured out an easy way to do this. The best approach I could find was:

- name: check out project from git
  delegate_to: localhost
  include_role: 
    name: configure_git

However, this doesn't work I get a complaint that there is a syntax error on the name line. If I remove the delegate_to line it works (but runs on the wrong server). If I replace include_role with debug it will run locally. It's almost as if ansible explicitly refuses to run an included role locally, not that I can find that anywhere in the documentation.

Is there a clean way to run this, or other roles, locally?

1 Answers

Extract from the include_role module documentation

  • Task-level keywords, loops, and conditionals apply only to the include_role statement itself.
  • To apply keywords to the tasks within the role, pass them using the apply option or use ansible.builtin.import_role instead.
  • Ignores some keywords, like until and retries.

I actually don't know if the error you get is linked to delegate_to being ignored (I seriously doubt it is the case...). Meanwhile it's not the correct way to use it here:

- name: check out project from git
  include_role: 
    name: configure_git
    apply:
      delegate_to: localhost

Moreover, this is most probably a bad idea. Let's imagine your play targets 100 servers: the role will run one hundred time (unless you also apply run_once: true). I would run my role "normally" on localhost in a dedicated play then do the rest of the job on my targets in the next one(s).

- name: Prepare env on localhost
  hosts: localhost
  roles:
    - role: configure_git

- name: Do the rest on other hosts
  hosts: my_group
  
  tasks:
    - name: dummy.
      debug:
        msg: "Dummy"
Related