Skip to content

Instantly share code, notes, and snippets.

@exoer
Forked from coderanger/db_server.rb
Created July 4, 2011 17:58
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save exoer/1063712 to your computer and use it in GitHub Desktop.
Save exoer/1063712 to your computer and use it in GitHub Desktop.
Create postgres users and databases from Chef
include_recipe "postgresql::server90"
# inspiration from
# https://gist.github.com/637579
execute "create-root-user" do
code = <<-EOH
psql -U postgres -c "select * from pg_user where usename='root'" | grep -c root
EOH
command "createuser -U postgres -s root"
not_if code
end
execute "create-database-user" do
code = <<-EOH
psql -U postgres -c "select * from pg_user where usename='#{node[:dbuser]}'" | grep -c #{node[:dbuser]}
EOH
command "createuser -U postgres -sw #{node[:dbuser]}"
not_if code
end
execute "create-database" do
exists = <<-EOH
psql -U postgres -c "select * from pg_database WHERE datname='#{node[:dbname]}'" | grep -c #{node[:dbname]}
EOH
command "createdb -U postgres -O #{node[:dbuser]} -E utf8 -T template0 #{node[:dbname]}"
not_if exists
end
# content in node.json
#{
# "postgresql" : {
# "version": 9.0,
# "dir": "/etc/postgresql/9.0/main"
# },
# "dbuser": "user",
# "dbname": "db"
#}
@honza
Copy link

honza commented Sep 12, 2011

Where should this code live?

@exoer
Copy link
Author

exoer commented Sep 12, 2011

I have it in a file on the path:
chef/cookbooks/postgresql/recipes/client.rb

@gerad
Copy link

gerad commented Jun 21, 2013

database_user in https://github.com/opscode-cookbooks/database also seems to accomplish this... (posting here since it was the first google result)

@mugwump
Copy link

mugwump commented Apr 10, 2014

I'm just now coming from this cookbook: Looks good in theory, but has a lot of unnecessary dependencies on other cookbooks like mysql, aws, xfs - I'd rather use something more focused on dealing with postgres...

@nkadel-skyhook
Copy link

The database cookbook is also very awkward to reliably reset a postgresql password with.

@gavvvr
Copy link

gavvvr commented Oct 29, 2017

Only r.entries[0]['count'] == '0' worked out for me

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