So I'm having a problem with a script used to automatically create shard replica sets in MongoDB.
The script is as follows:
#!/bin/bash
set -x
export shard_ips='[10.0.0.206,10.0.0.142,10.0.0.234]'
export shard_count=3
export replication_set_number=1
shard_count=$((shard_count-1))
IFS="," read -a shard_ips_arr <<< $(echo $shard_ips | tr -d '[]')
primary_shard_ip=${shard_ips_arr[0]}
count=0
while [ $count -le ${shard_count} ]
do
shard_ips_arr[$count]=$(echo { _id: $count, host: \"${shard_ips_arr[$count]}:27017\" } )
count=$(($count + 1))
done
function join { local IFS="$1"; shift; echo "$*"; }
shard_ips_arr=$(join , "${shard_ips_arr[@]}")
echo "${shard_ips_arr}"
echo "mongo --eval 'rs.initiate( { _id: \"shardreplset${replication_set_number}\", members: [ ${shard_ips_arr} ] } )' ${primary_shard_ip}:27017"
mongo --eval 'rs.initiate( { _id: "'shardreplset${replication_set_number}'", members: [ '${shard_ips_arr}' ] } )' ${primary_shard_ip}:27017
The purpose of the above script is to take in a string array passed from terraform and convert it into something that MongoDB can understand. A complete command should look like:
mongo --eval 'rs.initiate( { _id: "shardreplset1", members: [ { _id: 0, host: "10.0.0.206:27017" },{ _id: 1, host: "10.0.0.142:27017" },{ _id: 2, host: "10.0.0.234:27017" } ] } )' 10.0.0.206:27017
This will create a replica set of the three MongoDB servers using the primary shard (10.0.0.206:27017).
The issue is the inclusion of single quotes that bash seems to add to the variables. The debug output (using set -x) I receive from the last line of the script is as follows:
+ mongo --eval 'rs.initiate( { _id: "shardreplset1", members: [ {' _id: 0, host: '"10.0.0.206:27017"' '},{' _id: 1, host: '"10.0.0.142:27017"' '},{' _id: 2, host: '"10.0.0.234:27017"' '} ] } )' 10.0.0.206:27017
See all those extra single quotes in each item of $shard_ips_arr? Example:
{' _id: 0, host: '"10.0.0.206:27017"' '}
should look like { _id: 0, host: "10.0.0.206:27017" }
Does anyone know how to solve this issue?
And if you don't think that the single quotes are actually the issue, please let me know as well.
Please do also let me know if you want anything else clarifying.