mongoDB エラー「Failed: (Unauthorized) not authorized on admin to execute command」が発生した場合の対処法

mongoDB エラー「Failed: (Unauthorized) not authorized on admin to execute command」が発生した場合の対処法

mongoDBで、エラー「Failed: (Unauthorized) not authorized on admin to execute command」が発生した場合の対処法を記述してます。「mongostat」コマンドを使用することで確認できます。実行するには「roles:[“root”]」である必要があります。

環境

  • OS CentOS Stream release 9
  • MongoDB 6.0.2

手順

「mongostat」コマンド実行時に発生。

$ mongostat -u testuser -p pwd --authenticationDatabase admin

2022-11-01T21:53:42.095+0900    WARNING: On some systems, a password provided directly using --password may be visible to system status programs such as `ps` that may be invoked by other users. Consider omitting the password to provide it via stdin, or using the --config option to specify a configuration file with the password.
2022-11-01T21:53:42.115+0900    Failed: (Unauthorized) not authorized on admin to execute command { serverStatus: 1, recordStats: 0, lsid: { id: UUID("7ab60e7b-d5f3-4f77-b975-3f5caa3863e1") }, $db: "admin" }

原因

エラーメッセージにある通り「admin」で実行する権限がないため

対処法

対象のユーザに権限を付与します。

admin> db.grantRolesToUser("testuser", [{role:"root",db:"admin"}])
{ ok: 1 }

新しいユーザーを作る場合は、以下となります。

admin> db.createUser({user:"testuser", pwd:"pwd", roles:["root"]})