Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Last active August 29, 2015 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobiashm/6732eeb08c497178fd48 to your computer and use it in GitHub Desktop.
Save tobiashm/6732eeb08c497178fd48 to your computer and use it in GitHub Desktop.
Capistrano recipe for creating PostgreSQL database user
Capistrano::Configuration.instance(true).load do
namespace :db do
desc "Create database user for current site"
task :create_user, roles: :db do
config = Pathname.new(__dir__).join("..", "database.yml")
config = ERB.new(config.read).result(binding)
config = YAML.load(config)
fail "No database config for #{stage}" unless config[stage.to_s]
username, password = config[stage.to_s].values_at("username", "password")
run "#{sudo as: 'postgres'} psql -d postgres" do |channel, _, _|
channel.send_data(<<-SQL)
CREATE ROLE "#{username}" UNENCRYPTED PASSWORD '#{password}'
NOSUPERUSER CREATEDB NOCREATEROLE INHERIT LOGIN;
SQL
channel.send_data("\\q\n")
end
end
end
end
@tobiashm
Copy link
Author

tobiashm commented Feb 4, 2015

Expects the Capistrano MultiStage extension for the stage property, which is expected to match a Rails environment.
Also, that PostgreSQL CLI tools (psql) are installed on the server.
And that this file is located in a folder under (app-root)/config – e.g. in config/recipes/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment