Skip to content

Instantly share code, notes, and snippets.

@robske110
Last active June 11, 2021 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robske110/97249e9ccf41d0f15ed4e22705d81210 to your computer and use it in GitHub Desktop.
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.
#!/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