1

Let's say I have the following hosts groups in my Ansible inventory

[qrouters]
devops-qr1
devops-qr2

[shards]
devops-shrd1
devops-shrd2
devops-shrd3

I have to add shards to a mongodb cluster with a command similar as sh.addShard("<$REPLICASETNAME>/comma-separated-list-of-hosts") (ex: sh.addShard( "<replSetName>/s1-mongo1.example.net:27018,s1-mongo2.example.net:27018,s1-mongo3.example.net:27018")

I'd want to write that command in a templated file in my role (let's say roles/mongo_sharding/templates/addShards.j2), but do not know how to iterate through the inventory file.

Please keep in mind that the number of hosts in the [shards] group could change from time to time.

1

The template

$ cat addShards.j2
sh.addShard( "<{{ my_replica_set }}>/{{ my_hosts }}")

and the playbook

$ cat my_playbook.yml
- hosts: localhost

  vars:
    my_replica_set: "replSetName"
    my_group: "shards"

  tasks:

    - set_fact:
        my_hosts: "{{ groups[my_group]|join( ':27018,') ~ ':27018' }}"
    - template:
        src: addShards.j2
        dest: my_command

give

$ cat my_command 
sh.addShard( "<replSetName>/devops-shrd1:27018,devops-shrd2:27018,devops-shrd3:27018")
  • That simple... shows that I still need to beef up on Jinja filters ! – J.F.Gratton Feb 10 at 14:50

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.