how to run a shell command within a playbook repeatedly

Hi Team

Below is problem description on which i need help.

I am adding single mongo db shards by running below shell command – this is working fine to install on one server

  • name: “Creating the database”
    command: “sh /tmp/add_shard.sh {{item}} {{mongo_user}} {{mongo_password}}”
    register: mongo_db_shard_add
    ignore_errors: true

with_items: “{{P_NODE}}”
when: ansible_default_ipv4_address ==== “{{item}}”

here my Question :

Now i want to run add mutiple shards on multiple servers (example: add 3 shards on each servers). So how to change above code?

Basically , i want to run below command repeatedly in loop for "n’ number of time where n=number of shards to be added.
Also i should pass ‘n’ as input while running playbook

command: “sh /tmp/add_shard.sh {{item}} {{mongo_user}} {{mongo_password}} {{n}}”
where “n” is number of shards to be created"

Thanks
Hareesh

You can define a data structure, a dict for example containing number of shards per server an individual shard settings etc. Then just use with_sequence to iterate from 1 to length of the aforementioned shards list.

can you please help me changing below code as per your suggestion of with_sequence?

  • name: “Creating the database”
    command: “sh /tmp/add_shard.sh {{item}} {{mongo_user}} {{mongo_password}}”
    register: mongo_db_shard_add
    ignore_errors: true

with_items: “{{P_NODE}}”
when: ansible_default_ipv4_address ==== “{{item}}”

I would not run a shell script with the command module. You should use the script module instead. But ideally if you have the option use the mongodb_shard module.

This piece of code actually uses with_sequence to illustrate how to generate a sequence of numbers that will then used to populate port numbers dynamically: