I'm writing a bash script to that picks up a user password from an environment variable, hashes this, and inserts the results into a postgres database.
What I have works and looks fairly readable to me but I'm no expert on bash. Are there better conventions I could be following for what I'm doing?
#!/bin/bash
HASHED=$(echo -n $GUAC_PASSWORD | sha256sum | head -c 64)
PGPASSWORD=$POSTGRES_PASSWORD psql -U postgres << EOF
INSERT INTO guacamole_entity (name, type) VALUES ('guacadmin', 'USER');
INSERT INTO guacamole_user (entity_id, password_hash, password_salt, password_date)
SELECT
entity_id,
decode('${HASHED}', 'hex'),
null,
CURRENT_TIMESTAMP
FROM guacamole_entity WHERE name = 'guacadmin' AND guacamole_entity.type = 'USER';
EOF
Edit: I thought up a way to do it without sed feels neater to me.
Update: Thanks @OhMyGoodness and @TobySpeight! The conversations about passwords being in the clear got me twitchy enough to use docker secrets. So now I have the passwords in a file, not environment variables. PGPASSWORD
isn't actually needed as
The PostgreSQL image sets up trust authentication locally so you may notice a password is not required when connecting from localhost
The finalized script looks like this now:
#!/bin/bash
hashed=$(tr -d '\n' < /run/secrets/guac_password | sha256sum | tr -dc a-f0-9)
psql -U postgres << EOF
INSERT INTO guacamole_entity (name, type) VALUES ('guacadmin', 'USER');
INSERT INTO guacamole_user (entity_id, password_hash, password_salt, password_date)
SELECT
entity_id,
decode('${hashed}', 'hex'),
null,
CURRENT_TIMESTAMP
FROM guacamole_entity WHERE name = 'guacadmin' AND guacamole_entity.type = 'USER';
EOF