Last active
June 11, 2021 22:02
-
-
Save robske110/97249e9ccf41d0f15ed4e22705d81210 to your computer and use it in GitHub Desktop.
Postgres fast and secure user creation script. Usage: pgsqlcreateuser <username> [dbname] Prints generated password.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
pg_pw=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1) | |
sudo su postgres -c "psql -c \"DO \\$\\$ | |
BEGIN | |
IF EXISTS (SELECT FROM pg_roles WHERE rolname='$1') THEN | |
ALTER ROLE $1 WITH PASSWORD '$pg_pw'; | |
ELSE | |
CREATE USER $1 WITH PASSWORD '$pg_pw'; | |
END IF; | |
END \\$\\$;\"; $([ -z "$2" ] && echo "" || echo "createdb $2")" | |
echo "The generated password for $1 is:" | |
echo $pg_pw |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment