how to run a shell command within a playbook repeatedly

56 views
Skip to first unread message

Hareesh Vn

unread,
Oct 20, 2021, 3:02:20 AM10/20/21
to Ansible Project
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




Jorge Rúa

unread,
Oct 20, 2021, 5:25:18 AM10/20/21
to ansible...@googlegroups.com
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.

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/3a17346e-7abf-4cca-aa3a-a60445d2e380n%40googlegroups.com.

Hareesh Vn

unread,
Oct 20, 2021, 5:38:02 AM10/20/21
to Ansible Project

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}}"

Jorge Rúa

unread,
Oct 20, 2021, 8:07:43 PM10/20/21
to ansible...@googlegroups.com
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:


---
- name: Add shards
hosts: localhost
connection: local
gather_facts: false
vars:
start_port: 10000
total_shards: 3
tasks:
- name: Add mongodb shards
community.mongodb.mongodb_shard:
login_user: admin
login_password: admin
shard: "localhost:{{ item|int + start_port }}"
state: present
with_sequence: start=0 end="{{ total_shards - 1 }}"




Reply all
Reply to author
Forward
0 new messages