How to get hostInfo from all nodes in a replica set from Primary

Hi @venkata_reddy,

The db.hostinfo() shell helper calls the hostInfo administrative command, which must be executed against each replica set member.

However, you can iterate the replica set config and connect to each of the members. Here’s a quick example using the mongo shell:

rs.status().members.forEach(
    function(member) {
        print(`[${member._id}]: ${member.name}`);
        if (member.self) {
            printjson(db.adminCommand('hostInfo').os);
        } else {        
            try {
                var mdb = new Mongo(member.name);
                printjson(mdb.adminCommand('hostInfo').os);
            } catch (error) {
                print("Failed: " + printjson(error));
            }
        }
        print("");
    }
)

Note: the above snippet can be run via any member of the replica set. It doesn’t include authentication (you will need to call db.auth() with appropriate credentials), but should be a useful starting point. I used rs.status().members instead of rs.conf().members, because rs.status() includes the self field (no need to open a new connection to the current member) and some additional fields like health and state that might be interesting for logging/monitoring purposes.

For more robust error handling I recommend implementing this using one of the supported MongoDB drivers.

An alternative to rolling your own monitoring solution would be to use MongoDB Cloud Manager (hosted management platform) or MongoDB Ops Manager (on-premises management platform).

In one of your earlier questions (Health script from Ops manager) it sounded like you were already using Ops Manager.

Regards,
Stennie

2 Likes