How to use not_if in a chef recipe
I had been having the same issue. But, in my case, "not_if" seems executed by different user (root), and failed to check the condition properly. Adding [:user => "postgres"] resolved the issue.
execute "create-database-user" do user "postgres" exists = <<-EOH psql -U postgres -c "select * from pg_user where usename='#{settings[:username]}'" | grep -c #{settings[:username]} EOH command "createuser -U postgres -sw #{settings[:username]}" not_if exists, :user => "postgres"end
I've referred the following code example.
https://github.com/MarcinKoziuk/chef-postgres-dbsetup/blob/master/recipes/default.rb
You're checking for the existence of:
node[:user]
If it doesn't exist, you create:
node[:postgresql][:user]
Unless these happen to be equal, you'll keep trying to create node[:postgresql][:user] repeatedly.
First, there is a typo in the WHERE
condition. It should probably be username
instead of usename
.
Anyawy, you should do:
execute "create-user" do user "postgres" command "createuser -s #{node[:user]}" not_if "psql -U postgres -c \"select * from pg_user where username='#{node[:user]}'\" | grep -c #{node[:user]}"end
This assumes that your psql -U postgres -c "select * from pg_user where username='#{node[:user]}'"
is correct.
Same with a database:
execute "create-database" douser "postgres"command "createdb #{node[:database]}"not_if "psql -U postgres -c \"select * from pg_database WHERE datname='#{node[:database]}'\" | grep -c #{node[:database]}}"end
Regarding the username, even if it already exists, changing the password to the known one shouldn't cause a problem. After all you know the password.
FYI, you can define multiple conditionals within one resource.
Good luck with Chef! I love it very much!