How can I specify upload server in pypi upload? - pypi

Suppose I have a .pypirc file as,
[distutils]
index-servers =
pypi
test2
test3
test4
[pypi]
repository: https://test.pypi.org/legacy/
username: username_1
password: passme_1
[test2]
repository: url_1
username: username_1
password: passme_1
[test3]
repository: url_2
username: username_1
password: passme_1
[test4]
repository: url_3
username: username_1
password: passme_1
How can I upload to test4 profile without specifying --repository-url ?

twine upload --help:
…
-r REPOSITORY, --repository REPOSITORY
The repository (package index) to upload the package
to. Should be a section in the config file (default:
pypi). (Can also be set via TWINE_REPOSITORY
environment variable.)
…
So you should run twine upload -r test4.

Related

Fetch a file from task in same Ansible playbook

How do I transfer a file I have created from a previous task in my Ansible playbook? Here is what I got so far:
- name: Create Yum Report
shell: |
cd /tmp
yum history info > $(hostname -s)_$(date "+%d-%m-%Y").txt
register: after_pir
- name: Transfer PIR
fetch:
src: /tmp/{{ after_pir }}
dest: /tmp/
However, I receive this error message when I run my playbook.
TASK [Transfer PIR] ************************************************************************************************************
failed: [x.x.x.x] (item=after_pir) => {"ansible_loop_var": "item", "changed": false, "item": "after_pir", "msg": "the remote file does not exist, not transferring, ignored"}
I have tried to run different fetch, synchronzie and pull methods but I'm not sure what the issue is.
One way to do that:
- name: Create Yum Report
command: yum history info
register: yum_report
- name: Dump report on local disk for each host
copy:
content: "{{ yum_report.stdout }}"
dest: "/tmp/{{ inventory_hostname_short }}-{{ '%d-%m-%Y' | strftime }}"
delegate_to: localhost

How to configure Cypress for e2e in Github Actions?

I am trying to do an e2e test on my VueJS app that uses axios for API calls. In my vue component, in the mounted, i do an API call. My idea would be to mock this call with cy.intercept and cy.wait, however i can't make it work. On my local environment when i launch my frontend and backend servers, my test passes as the API call is made. However, the call is not silenced and the cy.wait('#apiCall') does not work.
Also my test does not work in Github Actions, i have this error : AxiosError: The following error originated from your application code, not from Cypress. It was caused by an unhandled promise rejection.. I have the impression that github actions need a special ci environment file but i don't know where to tell cypress to look into those env variables when in continous integration.
Anyone had the same issue or knows about cypress X axios X github actions combined ?
Some of my code :
test.cy.js
cy.intercept('GET', '/coaches/coach-informations/30283', {
data: {
email: 'hello#hello.com',
},
}).as('getCoach')
cy.visit('/hello?coach=30283')
cy.wait('#getCoach')
component.vue
async mounted() {
await axios.get(`/coaches/coach-informations/30283/`)
}
.env
API_URL=http://127.0.0.1:8000/api
test-frontend.yml
name: GitHub Actions Demo
on: [pull_request, push]
jobs:
cypress-run:
runs-on: ubuntu-latest
env:
working-directory: front
steps:
- name: Checkout
uses: actions/checkout#v3
- name: Install node
uses: actions/setup-node#v3
with:
node:version: 'node-version'
- name: Get yarn cache directory path 🛠
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
working-directory: ${{env.working-directory}}
- name: Cache node_modules 📦
uses: actions/cache#v2.1.7
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: yarn-${{ hashFiles('front/yarn.lock') }}
restore-keys: |
yarn-
- name: Install dependencies 👨🏻‍💻
working-directory: ${{env.working-directory}}
run: yarn
- name: Cypress run
uses: cypress-io/github-action#v2
with:
working-directory: ${{env.working-directory}}
build: yarn build
start: yarn vite
wait-on: 'http://localhost:3000'
wait-on-timeout: 120
config-file: cypress.config.js
record: true
env:
CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
I would say the URL used in the intercept is not catching the request from the app.
Locally you have a server running, so axios is ok but on Github the server is absent and the axios call fails.
It looks like you just need to add wildcard characters before the URL fragment
cy.intercept('GET', '**/coaches/coach-informations/30283', {
data: {
email: 'hello#hello.com',
},
}).as('getCoach')

AWS::CloudFormation::Init fails to create files from S3 Bucket although the retrieval via aws "s3 cp s3" is successful

I was trying to retreive a file from S3 Bucket during initialization of EC2 instance.
There are no failures (Syntax). But there is something missing.
The initial_setup.sh file is not created in the root directory
There are so many articles all state the same (or at least as per my humble understanding as newbie)
Parameters:
MyVPC: { Type: String, Default: vpc-000xxx }
myNstdKeyName: { Type: String, Default: xxx-key-test }
myNstdBucket: { Type: String, Default: myBucket }
myNstdEC2HostSubnet: { Type: String, Default: subnet-0xxxxx }
myNstdImageId: { Type: 'AWS::EC2::Image::Id', Default: 'ami-0xxxx' }
Resources:
#Allow incoming SSH and all types of outgoing traffic
SSHSecGrp4Pub:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Security group to allow SSH connection in public subnet
VpcId: !Ref MyVPC
SecurityGroupIngress: [ { IpProtocol: tcp, FromPort: 22, ToPort: 22, CidrIp: 0.0.0.0/0 } ]
SecurityGroupEgress: [ { IpProtocol: -1, CidrIp: 0.0.0.0/0, FromPort: 1, ToPort: 65535 } ]
#Assume Role
SAPEC2Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
RoleName: EC2AWSAccess
AssumeRolePolicyDocument:
Statement: [ { Effect: Allow, Principal: { Service: ec2.amazonaws.com } , Action: [ 'sts:AssumeRole' ] } ]
#Policy for the above role
S3RolePolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: "S3DownloadPolicy"
Roles: [ !Ref SAPEC2Role ]
PolicyDocument:
Statement:
- Effect: Allow
Action: [ 's3:GetObject' ]
Resource: !Sub "arn:aws:s3:::${myNstdBucket}/*"
#Profile for EC2 Instance
SAPEC2Profile:
Type: AWS::IAM::InstanceProfile
Properties: { InstanceProfileName: SAPEC2Profile, Roles: [ !Ref SAPEC2Role ] }
#My EC2 Instance
EC2:
Type: AWS::EC2::Instance
Metadata:
AWS::CloudFormation::Authentication:
S3Access:
type: "S3"
roleName: { Ref: "SAPEC2Role" }
buckets: [ !Ref myNstdBucket ]
AWS::CloudFormation::Init:
config:
files:
/root/initial_setup.sh: {
source: !Sub "https://${myNstdBucket}.s3.eu-central-1.amazonaws.com/initial_setup.sh",
mode: "000777",
owner: root,
group: root,
authentication: "S3Access"
}
commands:
myStarter:
command: "/bin/bash /root/initial_setup.sh"
Properties:
SubnetId: !Ref myNstdEC2HostSubnet
ImageId: !Ref myNstdImageId
InstanceType: t2.micro
KeyName: !Ref myNstdKeyName
IamInstanceProfile: !Ref SAPEC2Profile
SecurityGroupIds: [ !Ref SSHSecGrp4Pub ]
UserData:
Fn::Base64: !Sub |
#!/bin/bash
echo "my test file" > /root/testfile.txt
After the instance is initialized and i try it out with aws cp s3://mybucket/initial_setup.sh
It works but i have to go over with dos2unix.
The alternative would be to put it in UserData. But this should also work with commands. (^)
Someone also here had almost the same situation but it was mentioned that :
"For any commands to work we need to provide a shell environment in Userdata without which it cannot create any files"
And i added it too as a last line after the security group.
UserData:
Fn::Base64: !Sub |
#!/bin/bash
echo "my test file" > /root/testfile.txt
So the /root/testfile.txt gets created with the specified text in it.
But the required file from the bucket did not show up.
i had a misconception that just by stating Metadata Stuff, it will get executed as well. But now i'm half way through.
This was the missing part under the UserData
UserData:
Fn::Base64: !Sub |
cd /tmp
wget https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz
gzip -df aws-cfn-bootstrap-latest.tar.gz
tar -xvf aws-cfn-bootstrap-latest.tar
chmod -R 755 /tmp/aws-cfn-bootstrap-1.4
pip install --upgrade pip
pip install --upgrade setuptools
pip install awscli --ignore-installed six &> /dev/null
export PYTHONPATH=/tmp/aws-cfn-bootstrap-1.4
/tmp/aws-cfn-bootstrap-1.4/bin/cfn-init -v --stack ${AWS::StackName} --resource EC2 --region ${AWS::Region}
It is actually the last line which makes the difference. The lines before it were used to setup the configuration as the image used is a non-aws image. So it does not bring the capability out of the box.

Ansible and ForwardAgent for sudo_user

Could someone say me, what am I doing wrong? I'm working with Amazon EC2 instance and want to have agent forwarded to user rails, but when I run next task:
- acl: name={{ item }} etype=user entity=rails permissions=rwx state=present
with_items:
- "{{ ansible_env.SSH_AUTH_SOCK|dirname }}"
- "{{ ansible_env.SSH_AUTH_SOCK }}"
sudo: true
I see failed result:
(item=/tmp/ssh-ULvzaZpq2U) => {"failed": true, "item": "/tmp/ssh-ULvzaZpq2U"}
msg: path not found or not accessible!
When I try to it manually, without ansible, it looks good:
setfacl -m rails:rwx "$SSH_AUTH_SOCK"
setfacl -m rails:x $(dirname "$SSH_AUTH_SOCK")
sudo -u rails ssh -T git#github.com //Hi KELiON! You've successfully authenticated, but GitHub does not provide shell access.
I even tried to run new instance and run test ansible playbook:
#!/usr/bin/env ansible-playbook
---
- hosts: all
remote_user: ubuntu
tasks:
- user: name=rails
sudo: true
- name: Add ssh agent line to sudoers
lineinfile:
dest: /etc/sudoers
state: present
regexp: SSH_AUTH_SOCK
line: Defaults env_keep += "SSH_AUTH_SOCK"
sudo: true
- acl: name={{ item }} etype=user entity=rails permissions=rwx state=present
with_items:
- "{{ ansible_env.SSH_AUTH_SOCK|dirname }}"
- "{{ ansible_env.SSH_AUTH_SOCK }}"
sudo: true
- name: Test that git ssh connection is working.
command: ssh -T git#github.com
sudo: true
sudo_user: rails
ansible.cfg is:
[ssh_connection]
pipelining=True
ssh_args=-o ForwardAgent=yes -o ControlMaster=auto -o ControlPersist=60s
[defaults]
sudo_flags=-HE
hostfile=staging
But the same result. Any ideas?
I had the same issue and found the answer at https://github.com/ansible/ansible/issues/7235#issuecomment-45842303
My solution varied a bit from his, because acl didn’t work for me, so I:
Changed ansible.cfg:
[defaults]
sudo_flags=-HE
[ssh_connection]
# COMMENTED OUT: ssh_args = -o ForwardAgent=yes
Added tasks/ssh_agent_hack.yml containing:
- name: "(ssh-agent hack: grant access to {{ deploy_user }})"
# SSH-agent socket is forwarded for the current user only (0700 file). Let's change it
# See: https://github.com/ansible/ansible/issues/7235#issuecomment-45842303
# See: http://serverfault.com/questions/107187/ssh-agent-forwarding-and-sudo-to-another-user
become: false
file: group={{deploy_user}} mode=g+rwx path={{item}}
with_items:
- "{{ ansible_env.SSH_AUTH_SOCK|dirname }}"
- "{{ ansible_env.SSH_AUTH_SOCK }}"
NOTE - the become: false setting is because I ssh in as root - If you ssh in as something else, then you will need to become root to do the fix, and then below become your deploy_user (if it isnt the user you are ssh'ing in as).
And then called it from my deploy.yml playbook:
- hosts: apps
gather_facts: True
become: True
become_user: "{{deploy_user}}"
pre_tasks:
- include: tasks/ssh_agent_hack.yml
tags: [ 'deploy' ]
roles:
- { role: carlosbuenosvinos.ansistrano-deploy, tags: [ 'deploy' ] }
Side note - Adding ForwardAgent yes to the host entry in ~/.ssh/config didn't affect what worked (I tried all 8 combinations :- only setting sudo_flags but not ssh_args works but it doesn't matter if you set forwarding on or off in ~/.ssh/config for opensssh - tested under ubuntu trusty)
Also note: I have pipelining=True in ansible.cfg
This worked for me in ansible v2.3.0.0:
$ vi ansible.cfg
[defaults]
roles_path = ./roles
retry_files_enabled = False
[ssh_connection]
ssh_args=-o ControlMaster=auto -o ControlPersist=60s -o ControlPath=/tmp/ansible-ssh-%h-%p-%r -o ForwardAgent=yes
$ vi roles/pull-code/tasks/main.yml
- name: '(Hack: keep SSH forwarding socket)'
lineinfile:
dest: /etc/sudoers
insertafter: '^#?\s*Defaults\s+env_keep\b'
line: 'Defaults env_keep += "SSH_AUTH_SOCK"'
- name: '(Hack: grant access to the socket to {{app_user}})'
become: false
acl: name='{{item}}' etype=user entity='{{app_user}}' permissions="rwx" state=present
with_items:
- "{{ ansible_env.SSH_AUTH_SOCK|dirname }}"
- "{{ ansible_env.SSH_AUTH_SOCK }}"
- name: Pull the code
become: true
become_user: '{{app_user}}'
git:
repo: '{{repository}}'
dest: '{{code_dest}}'
accept_hostkey: yes
I know this answer is late to the party, but the other answers seemed a bit overly complicated when I distilled my solution to the bare minimum. Here's an example playbook to clone a git repo that requires authentication for access via ssh:
- hosts: all
connection: ssh
vars:
# forward agent so access to git via ssh works
ansible_ssh_extra_args: '-o ForwardAgent=yes'
utils_repo: "git#git.example.com:devops/utils.git"
utils_dir: "/opt/utils"
tasks:
- name: Install Utils
git:
repo: "{{ utils_repo }}"
dest: "{{ utils_dir }}"
update: true
accept_hostkey: yes
become: true
become_method: sudo
# Need this to ensure we have the SSH_AUTH_SOCK environment variable
become_flags: '-HE'

How to secure MongoDB with username and password

I want to set up user name & password authentication for my MongoDB instance, so that any remote access will ask for the user name & password. I tried the tutorial from the MongoDB site and did following:
use admin
db.addUser('theadmin', '12345');
db.auth('theadmin','12345');
After that, I exited and ran mongo again. And I don't need password to access it. Even if I connect to the database remotely, I am not prompted for user name & password.
UPDATE Here is the solution I ended up using
1) At the mongo command line, set the administrator:
use admin;
db.addUser('admin','123456');
2) Shutdown the server and exit
db.shutdownServer();
exit
3) Restart mongod with --auth
$ sudo ./mongodb/bin/mongod --auth --dbpath /mnt/db/
4) Run mongo again in 2 ways:
i) run mongo first then login:
$ ./mongodb/bin/mongo localhost:27017
use admin
db.auth('admin','123456');
ii) run & login to mongo in command line.
$ ./mongodb/bin/mongo localhost:27017/admin -u admin -p 123456
The username & password will work the same way for mongodump and mongoexport.
You need to start mongod with the --auth option after setting up the user.
From the MongoDB Site:
Run the database (mongod process) with the --auth option to enable
security. You must either have added a user to the admin db before
starting the server with --auth, or add the first user from the
localhost interface.
MongoDB Authentication
Wow so many complicated/confusing answers here.
This is as of v3.4.
Short answer.
Start MongoDB without access control (/data/db or where your db is).
mongod --dbpath /data/db
Connect to the instance.
mongo
Create the user.
use some_db
db.createUser(
{
user: "myNormalUser",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "some_db" },
{ role: "read", db: "some_other_db" } ]
}
)
Stop the MongoDB instance and start it again with access control.
mongod --auth --dbpath /data/db
Connect and authenticate as the user.
use some_db
db.auth("myNormalUser", "xyz123")
db.foo.insert({x:1})
use some_other_db
db.foo.find({})
Long answer: Read this if you want to properly understand.
It's really simple. I'll dumb the following down https://docs.mongodb.com/manual/tutorial/enable-authentication/
If you want to learn more about what the roles actually do read more here: https://docs.mongodb.com/manual/reference/built-in-roles/
Start MongoDB without access control.
mongod --dbpath /data/db
Connect to the instance.
mongo
Create the user administrator. The following creates a user administrator in the admin authentication database. The user is a dbOwner over the some_db database and NOT over the admin database, this is important to remember.
use admin
db.createUser(
{
user: "myDbOwner",
pwd: "abc123",
roles: [ { role: "dbOwner", db: "some_db" } ]
}
)
Or if you want to create an admin which is admin over any database:
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Stop the MongoDB instance and start it again with access control.
mongod --auth --dbpath /data/db
Connect and authenticate as the user administrator towards the admin authentication database, NOT towards the some_db authentication database. The user administrator was created in the admin authentication database, the user does not exist in the some_db authentication database.
use admin
db.auth("myDbOwner", "abc123")
You are now authenticated as a dbOwner over the some_db database. So now if you wish to read/write/do stuff directly towards the some_db database you can change to it.
use some_db
//...do stuff like db.foo.insert({x:1})
// remember that the user administrator had dbOwner rights so the user may write/read, if you create a user with userAdmin they will not be able to read/write for example.
More on roles: https://docs.mongodb.com/manual/reference/built-in-roles/
If you wish to make additional users which aren't user administrators and which are just normal users continue reading below.
Create a normal user. This user will be created in the some_db authentication database down below.
use some_db
db.createUser(
{
user: "myNormalUser",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "some_db" },
{ role: "read", db: "some_other_db" } ]
}
)
Exit the mongo shell, re-connect, authenticate as the user.
use some_db
db.auth("myNormalUser", "xyz123")
db.foo.insert({x:1})
use some_other_db
db.foo.find({})
Last but not least due to users not reading the commands I posted correctly regarding the --auth flag, you can set this value in the configuration file for mongoDB if you do not wish to set it as a flag.
First, un-comment the line that starts with #auth=true in your mongod configuration file (default path /etc/mongod.conf). This will enable authentication for mongodb.
Then, restart mongodb : sudo service mongod restart
This answer is for Mongo 3.2.1
Reference
Terminal 1:
$ mongod --auth
Terminal 2:
db.createUser({user:"admin_name", pwd:"1234",roles:["readWrite","dbAdmin"]})
if you want to add without roles (optional):
db.createUser({user:"admin_name", pwd:"1234", roles:[]})
to check if authenticated or not:
db.auth("admin_name", "1234")
it should give you:
1
else :
Error: Authentication failed.
0
Here is a javascript code to add users.
Start mongod with --auth = true
Access admin database from mongo shell and pass the javascript file.
mongo admin "Filename.js"
"Filename.js"
// Adding admin user
db.addUser("admin_username", " admin_password");
// Authenticate admin user
db.auth("admin_username ", " admin_password ");
// use database code from java script
db = db.getSiblingDB("newDatabase");
// Adding newDatabase database user
db.addUser("database_username ", " database_ password ");
Now user addition is complete, we can verify accessing the database from mongo shell
https://docs.mongodb.com/manual/reference/configuration-options/#security.authorization
Edit the mongo settings file;
sudo nano /etc/mongod.conf
Add the line:
security.authorization : enabled
Restart the service
sudo service mongod restart
Regards
You could change /etc/mongod.conf.
Before
#security:
After
security:
authorization: "enabled"
Then sudo service mongod restart
First run mongoDB on terminal using
mongod
now run mongo shell use following commands
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Re-start the MongoDB instance with access control.
mongod --auth
Now authenticate yourself from the command line using
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
I read it from
https://docs.mongodb.com/manual/tutorial/enable-authentication/
This is what I did on Ubuntu 18.04:
$ sudo apt install mongodb
$ mongo
> show dbs
> use admin
> db.createUser({ user: "root", pwd: "rootpw", roles: [ "root" ] }) // root user can do anything
> use lefa
> db.lefa.save( {name:"test"} )
> db.lefa.find()
> show dbs
> db.createUser({ user: "lefa", pwd: "lefapw", roles: [ { role: "dbOwner", db: "lefa" } ] }) // admin of a db
> exit
$ sudo vim /etc/mongodb.conf
auth = true
$ sudo systemctl restart mongodb
$ mongo -u "root" -p "rootpw" --authenticationDatabase "admin"
> use admin
> exit
$ mongo -u "lefa" -p "lefapw" --authenticationDatabase "lefa"
> use lefa
> exit
User creation with password for a specific database to secure database access :
use dbName
db.createUser(
{
user: "dbUser",
pwd: "dbPassword",
roles: [ "readWrite", "dbAdmin" ]
}
)
Follow the below steps in order
Create a user using the CLI
use admin
db.createUser(
{
user: "admin",
pwd: "admin123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
Enable authentication, how you do it differs based on your OS, if you are using windows you can simply mongod --auth in case of linux you can edit the /etc/mongod.conf file to add security.authorization : enabled and then restart the mongd service
To connect via cli mongo -u "admin" -p "admin123" --authenticationDatabase "admin". That's it
You can check out this post to go into more details and to learn connecting to it using mongoose.
This is what i did for ubuntu 20.04 and mongodb enterprise 4.4.2:
start mongo shell by typing mongo in terminal.
use admin database:
use admin
create a new user and assign your intended role:
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: passwordPrompt(), // or cleartext password
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
exit mongo and add the following line to etc/mongod.conf:
security:
authorization: enabled
restart mongodb server
(optional) 6.If you want your user to have root access you can either specify it when creating your user like:
db.createUser(
{
user: "myUserAdmin",
pwd: passwordPrompt(), // or cleartext password
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
or you can change user role using:
db.grantRolesToUser('admin', [{ role: 'root', db: 'admin' }])
Some of the answers are sending mixed signals between using --auth command line flag or setting config file property.
security:
authorization: enabled
I would like to clarify that aspect. First of all, authentication credentials (ie user/password) in both cases has to be created by executing db.createUser query on the default admin database. Once credentials are obtained, there are two ways to enable authentication:
Without a custom config file: This is when the former auth flag is applicable. Start mongod like: usr/bin/mongod --auth
With a custom config file: This is when the latter configs has to be present in the custom config file.Start mongod like: usr/bin/mongod --config <config file path>
To connect to the mongo shell with authentication:
mongo -u <user> -p <password> --authenticationDatabase admin
--authenticationDatabase here is the database name where the user was created. All other mongo commands like mongorestore, mongodump accept the additional options ie -u <user> -p <password> --authenticationDatabase admin
Refer to https://docs.mongodb.com/manual/tutorial/enable-authentication/ for details.
The best practice to connect to mongoDB as follow:
After initial installation,
use admin
Then run the following script to create admin user
db.createUser(
{
user: "YourUserName",
pwd: "YourPassword",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }
]
})
the following script will create the admin user for the DB.
log into the db.admin using
mongo -u YourUserName -p YourPassword admin
After login, you can create N number of the database with same admin credential or different by repeating the 1 to 3.
This allows you to create different user and password for the different collection you creating in the MongoDB
mongodb 4.4.13 community
1. create database user
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
1.2 verify working
> db.auth('myUserAdmin','abc123')
< { ok: 1 }
if it fails you get
> db.auth('myUserAdmin','amongus')
MongoServerError: Authentication failed.
2. modify /etc/mongod.conf
nano /etc/mongod.conf
change:
#security:
to:
security:
authorization: enabled
3. restart mongod service
sudo service mongod restart
this is what worked for me.
These steps worked on me:
write mongod --port 27017 on cmd
then connect to mongo shell : mongo --port 27017
create the user admin :
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
disconnect mongo shell
restart the mongodb : mongod --auth --port 27017
start mongo shell :
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
To authenticate after connecting, Connect the mongo shell to the mongod:
mongo --port 27017
switch to the authentication database :
use admin
db.auth("myUserAdmin", "abc123"
You'll need to switch to the database you want the user on (not the admin db) ...
use mydatabase
See this post for more help ... https://web.archive.org/web/20140316031938/http://learnmongo.com/posts/quick-tip-mongodb-users/
after you create new user, please don't forget to grant read/write/root permission to the user. you can try the
cmd: db.grantRolesToUser('yourNewUsername',[{ role: "root", db: "admin" }])
Many duplicate answers but I think they miss an important note:
Even when authentication is enabled properly you can connect to the Mongo database without username/password!
However, you can execute only harmless commands like db.help(), db.getMongo(), db.listCommands(), etc.
$ mongo
MongoDB shell version v4.4.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("f662858b-8658-4e33-a735-120e3639c131") }
MongoDB server version: 4.4.3
mongos> db.getMongo()
connection to 127.0.0.1:27017
mongos> db
test
mongos> db.version()
4.4.3
mongos> db.runCommand({connectionStatus : 1})
{
"authInfo" : {
"authenticatedUsers" : [ ],
"authenticatedUserRoles" : [ ]
},
"ok" : 1,
"operationTime" : Timestamp(1618996970, 2),
"$clusterTime" : {
"clusterTime" : Timestamp(1618996970, 2),
"signature" : {
"hash" : BinData(0,"Kre9jvnJvsW+OVCl1QC+eKSBbbY="),
"keyId" : NumberLong("6944343118355365892")
}
}
}
I have done this in version 6.0
how to set user name and password for a database;
install MongoDB 6.0 or higher
create database(whatever the name may be) in MongoDB using compass
install MongoDB Shell
https://www.mongodb.com/try/download/shell
open cmd
cd C:\Program Files\mongosh
mongosh "mongodb://localhost:27017"
use #your database name#
db.createUser( { user: "xxx", pwd: "xxx", roles: [ { role: "readWrite", db: "xxx" } ] } )