Every quarter, the audit team requests a list of users and the timestamps of when they were created. So, I created a simple shell script to automate user creation and log the details into a table.
in this case I store the table in the testdb
database
1) Create the table for store the data
CREATE TABLE user_log (
username TEXT,
created_at TIMESTAMP
);
2) This is the shell script (create_pg_user.sh
)
#!/bin/bash
# Check if a username was provided
if [ -z "$1" ]; then
echo "Usage: $0 <username>"
exit 1
fi
USERNAME=$1
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
PGUSER="postgres"
PGDATABASE="testdb"
PGHOST="localhost"
PGPORT="5432"
psql -U $PGUSER -d $PGDATABASE -h $PGHOST -p $PGPORT -c "CREATE USER $USERNAME;"
psql -U $PGUSER -d $PGDATABASE -h $PGHOST -p $PGPORT -c \
"INSERT INTO user_log (username, created_at) VALUES ('$USERNAME', '$TIMESTAMP');"
3) Execute the shell script. here I just put the username and the password will be auto generated.
sh create_pg_user.sh myuser
CREATE ROLE
INSERT 0 1
User created successfully!
Username: myuser
Password: k4EM99fNRdCC2spj
4) Let's check user created date
postgres=# \du
List of roles
Role name | Attributes | Member of
---------------+------------------------------------------------------------+--------------
myuser | | {}
testdb=# select * from user_log;
username | created_at
----------+---------------------
myuser | 2025-06-20 12:13:23
(2 rows)
so whenever the audit team asks when a user was created, we can provide the information by selecting user_log
table
Top comments (0)