Login into MongoDB


#1

The following script will SSH to a Juju 2.0 controller machine and start a mongo shell. It optionally takes the machine to connect to and the model name (defaulting to machine “0” in the model named “controller”).

#!/bin/bash

machine=${1:-0}
model=${2:-controller}

read -d '' -r cmds <<'EOF'
conf=/var/lib/juju/agents/machine-*/agent.conf
user=`sudo grep tag $conf | cut -d' ' -f2`
password=`sudo grep statepassword $conf | cut -d' ' -f2`
if [ -f /usr/lib/juju/mongo*/bin/mongo ]; then
  client=/usr/lib/juju/mongo*/bin/mongo
else
  client=/usr/bin/mongo
fi
$client 127.0.0.1:37017/juju --authenticationDatabase admin --ssl --sslAllowInvalidCertificates --username "$user" --password "$password"
EOF

juju ssh -m $model $machine "$cmds"

#2

This is very similar to mine. My one uses a PATH expansion to deal with the different mongo versions.

Also, I have it saved as juju-db in ~/bin which is in my PATH, which means I can do the following:

juju db

Script contents:

#!/bin/bash

machine=${1:-0}
model=${2:-controller}

echo machine $machine

read -d '' -r cmds <<'EOF'
conf=/var/lib/juju/agents/machine-*/agent.conf
user=`sudo grep tag $conf | cut -d' ' -f2`
password=`sudo grep statepassword $conf | cut -d' ' -f2`
PATH="$PATH:$(echo /usr/lib/juju/mongo*/bin)"
mongo 127.0.0.1:37017/juju --authenticationDatabase admin --ssl --sslAllowInvalidCertificates --username "$user" --password "$password"
EOF

juju ssh -m $model $machine "$cmds"

I think perhaps the echo left in there was from me debugging at some stage.


#3

That does works, though on Bionic it adds a literal “/usr/lib/juju/mongo*/bin” to PATH if it doesn’t exist. It isn’t a huge deal, as a PATH that doesn’t exist doesn’t match anything. :slight_smile: