Generate hosts file and parameter on the fly

Viewed 123

I am preparing to write an Ansible playbook that will deploy an Elasticsearch cluster with docker containers (and later use this same technique for other things).

My goal is to supply a number (an integer), and with this number Ansible will generate a list of hosts and other parameters it needs for the deployment.

for example, if I supply a number like 3, then Ansible will deploy the named containers:

  • elastic-1
  • elastic-2
  • elastic-3

on hosts:

  • host-1
  • host-2
  • host-3

I found this article that seems to fit my needs: https://docs.ansible.com/ansible/2.10/collections/ansible/builtin/generator_inventory.html but I can't figure out how to use an integer like I described.

1 Answers

You can simply use the module add_host with a loop and the range filter.

Given the playbook:

- hosts: localhost
  gather_facts: no

  vars_prompt:
    name: elastic_hosts
    prompt: How many containers do you want?
    private: no

  tasks:
    - ansible.builtin.add_host:
        name: "host-{{ item }}"
        container_name: "elastic-{{ item }}"
        groups: elastic
      loop: "{{ range(1, (elastic_hosts|int + 1)) }}"

- hosts: elastic
  gather_facts: no

  tasks:
    - ansible.builtin.debug:
        var: container_name

Would give:

How many containers do you want?: 3

PLAY [localhost] ********************************************************

TASK [ansible.builtin.add_host] ******************************************
ok: [localhost] => (item=1)
ok: [localhost] => (item=2)
ok: [localhost] => (item=3)

PLAY [elastic] **********************************************************

TASK [ansible.builtin.debug] ********************************************
ok: [host-1] => 
  container_name: elastic-1
ok: [host-2] => 
  container_name: elastic-2
ok: [host-3] => 
  container_name: elastic-3    
Related