Search code examples
ansibleansible-inventory

Using Ansible per directory instead of per host


I know it will sound a bit strange but I wonder if there is a way to use Ansible per directory instead of per host.

Our current use case is the following: the same application (here WordPress) is deployed into multiple folders onto the same host (probably a very common scenario at a hosting provider).

We want to manage the configuration of all the instances in a 'smart' way (hence the idea of using Ansible). for instance, the same file (plugin) should be copied into the same subfolders of the instances.

This could be very easily achieved if all instances were hosted on different hosts, but I can find a way to achieve this in different folders on the same host.

Is that completely stupid? Is there a better tool to do that? Any insight will be greatly appreciated.


Solution

  • You can define different host aliases for the same physical host (or VM) like this:

    hosts:

    host_user1 ansible_host=host1.example.com app_root_path=/apps/user_john
    host_user2 ansible_host=host1.example.com app_root_path=/apps/user_peter
    host_user3 ansible_host=host2.example.com app_root_path=/apps/user_smith
    

    this way you will have three "hosts", but host_user1 and host_user2 is the same physical host host1.example.com, whereas host_user3 is actually host2.example.com. Variable app_root_path is specific for every host. So you can do something like this in your playbook:

    - hosts: all
      tasks:
        - unarchive:
            src: myapp_dist.tgz
            dest: "{{ app_root_path }}/myapp/"
    

    This will extract myapp_dist.tgz to three different directories.

    But be aware that with this approach you can have troubles with modules that require exclusive locks per host (like apt).