mongodb query

반응형

MongoDB admin user 생성 하기

실습 전에 docker, docker-compose, 그리고 MongoDB 컨테이너가 구성된 yml 파일이 필요한데, 이전 블로그를 참고해도 좋습니다.
[MongoDB docker-compose로 구성 하기]

MongoDB 컨테이너가 설치되었다는 가정하에 먼저 docker ps 명령어로 컨테이너 정보를 조회 합니다.

$docker ps
CONTAINER ID   IMAGE         COMMAND                  CREATED       STATUS       PORTS                                 NAMES
dc0c851d73a7   mongo:4.4.5   "/usr/bin/mongod --b…"   2 hours ago   Up 2 hours   0.0.0.0:27017->27017/tcp              mongo1

MongoDB admin user 생성을 위해 docker 컨테이너 터미널로 접속해 보겠습니다.

$docker exec -it mongo1 bash  //container terminal 접속

root@dc0c851d73a7:/# mongo
MongoDB shell version v4.4.5
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("7de3fbdb-078a-476c-8003-fcd12c1dd105") }
MongoDB server version: 4.4.5
---
The server generated these startup warnings when booting:
        2022-06-30T03:40:07.230+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
        2022-06-30T03:40:07.727+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2022-06-30T03:40:07.727+00:00: You are running this process as the root user, which is not recommended
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

이제 admin db로 이동하여 순서대로 진행해 봅니다. 그 전에 replica 설정이 안되어 있을 경우 user 계정 생성이 불가할 수 있습니다.
admin db 이동 후 rs.status() 명령어로 replica set 상태를 확인해 봅니다.

> use admin       //admin db 이동
switched to db amdin

> rs.status()
{
    "ok" : 0,
    "errmsg" : "no replset config has been received",
    "code" : 94,
    "codeName" : "NotYetInitialized"
}

> db.createUser(
...   {
...      user: "admin",
...      pwd: passwordPrompt(), // or cleartext password
...      roles: [ { role: "root", db: "admin" } ]
...   }
... )  //replica 설정이 없어서 아래 오류 발생함.
Enter password:
uncaught exception: Error: couldn't add user: not master :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.createUser@src/mongo/shell/db.js:1386:11
@(shell):1:1

이제 다시 rs.initiate() 명령어로 default replica 정보를 설정합니다. 아래와 같이 변경된 커맨드로 전환되면 됩니다.
그리고 rs.status() 명령어로 설정을 재확인 합니다.

> rs.initiate()   //replica default 설정
r0:SECONDARY>


r0:PRIMARY> rs.status() 
{
    "set" : "r0",
    "date" : ISODate("2022-06-30T04:12:32.988Z"),
    "myState" : 1,
    "term" : NumberLong(1),
    "syncSourceHost" : "",
    "syncSourceId" : -1,
    "heartbeatIntervalMillis" : NumberLong(2000),
    "majorityVoteCount" : 1,
    "writeMajorityCount" : 1,
    "votingMembersCount" : 1,
    "writableVotingMembersCount" : 1,
    "optimes" : {
        "lastCommittedOpTime" : {
            "ts" : Timestamp(1656562345, 1),
            "t" : NumberLong(1)
        },
        "lastCommittedWallTime" : ISODate("2022-06-30T04:12:25.854Z"),
        "readConcernMajorityOpTime" : {
            "ts" : Timestamp(1656562345, 1),
            "t" : NumberLong(1)
        },
        "readConcernMajorityWallTime" : ISODate("2022-06-30T04:12:25.854Z"),
        "appliedOpTime" : {
            "ts" : Timestamp(1656562345, 1),
            "t" : NumberLong(1)
        },
        "durableOpTime" : {
            "ts" : Timestamp(1656562345, 1),
            "t" : NumberLong(1)
        },
        "lastAppliedWallTime" : ISODate("2022-06-30T04:12:25.854Z"),
        "lastDurableWallTime" : ISODate("2022-06-30T04:12:25.854Z")
    },
    "lastStableRecoveryTimestamp" : Timestamp(1656562335, 1),
    "electionCandidateMetrics" : {
        "lastElectionReason" : "electionTimeout",
        "lastElectionDate" : ISODate("2022-06-30T04:03:15.746Z"),
        "electionTerm" : NumberLong(1),
        "lastCommittedOpTimeAtElection" : {
            "ts" : Timestamp(0, 0),
            "t" : NumberLong(-1)
        },
        "lastSeenOpTimeAtElection" : {
            "ts" : Timestamp(1656561795, 1),
            "t" : NumberLong(-1)
        },
        "numVotesNeeded" : 1,
        "priorityAtElection" : 1,
        "electionTimeoutMillis" : NumberLong(10000),
        "newTermStartDate" : ISODate("2022-06-30T04:03:15.778Z"),
        "wMajorityWriteAvailabilityDate" : ISODate("2022-06-30T04:03:15.853Z")
    },
    "members" : [
        {
            "_id" : 0,
            "name" : "dc0c851d73a7:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 1945,
            "optime" : {
                "ts" : Timestamp(1656562345, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2022-06-30T04:12:25Z"),
            "syncSourceHost" : "",
            "syncSourceId" : -1,
            "infoMessage" : "",
            "electionTime" : Timestamp(1656561795, 2),
            "electionDate" : ISODate("2022-06-30T04:03:15Z"),
            "configVersion" : 1,
            "configTerm" : 1,
            "self" : true,
            "lastHeartbeatMessage" : ""
        }
    ],
    "ok" : 1,
    "$clusterTime" : {
        "clusterTime" : Timestamp(1656562345, 1),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    },
    "operationTime" : Timestamp(1656562345, 1)
}

다시 db.createUser() 명령어를 실행하여 admin user 생성을 시도하면 아래 처럼 successfully 메세지와 생성된 계정 정보를 확인할 수 있습니다.
이때 password는 Prompt or cleartext 형태로 진행할 수 있습니다.

//role type: root, readWrite, dbOwner
r0:PRIMARY> db.createUser(
...   {
...      user: "admin",
...      pwd: passwordPrompt(), // or cleartext password
...      roles: [{ role: "root", db: "admin" }]
...   }
... )
Enter password:
Successfully added user: {
    "user" : "admin",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}
r0:PRIMARY>

이제 생성된 계정으로 MongoDB 명령어를 사용해 봅니다.

r0:PRIMARY> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

오늘은 MongoDB에서 admin user 생성하는 방법에 대하여 정리해 봤습니다.

반응형

+ Recent posts

반응형