How to use not_if in a chef's recipe

I'm new to the cook, so I'm a little confused about how conditional not_if works inside the execute resource. I understand that he tells the chef not to execute the command if the command returns 0 or true; however, in my code, the command apparently still runs.

The following code should create a user (and his password) and a database; however, if the user and the database already exist, he should not do anything. User, database and password are defined in the attributes. Below is the code I have:

execute "create-user" do

        code = <<-EOH
        psql -U postgres -c "select * from pg_user where usename='#{node[:user]}'" | grep -c #{node[:user]}
        EOH
        user "postgres"
        command "createuser -s #{node[:user]}"
        not_if code
end


execute "set-user-password" do
    user "postgres"
    command  "psql -U postgres -d template1 -c \"ALTER USER #{node[:user]} WITH PASSWORD '#{node[:password]}';\""
end


execute "create-database" do
    exists = <<-EOH
    psql -U postgres -c "select * from pg_database WHERE datname='#{node[:database]}'" | grep -c #{node[:database]}}
    EOH
    user "postgres"
    command "createdb #{node[:database]}"
   not_if exists

end

The chef gives me the following error:

Error executing the action runon resource 'execute [create-user]'

...

[2013-01-25T12: 24: 51-08: 00] FATAL: Mixlib:: ShellOut:: ShellCommandFailed: [create-user] (postgresql:: initialize line 16) : Mixlib:: ShellOut:: ShellCommandFailed: [0], "1"

STDERR: createuser: : ERROR: ""

, , . - ?

+5
3

. , , "not_if", , (root), . [: user = > "postgres" ] .

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

.

https://github.com/MarcinKoziuk/chef-postgres-dbsetup/blob/master/recipes/default.rb

+3

:

node[:user]

, :

node[:postgresql][:user]

, node [: postgresql] [: user].

+1

-, WHERE . , username usename.

Anyawy, :

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

, psql -U postgres -c "select * from pg_user where username='#{node[:user]}'" .

:

execute "create-database" do
user "postgres"
command "createdb #{node[:database]}"
not_if "psql -U postgres -c \"select * from pg_database WHERE datname='#{node[:database]}'\" | grep -c #{node[:database]}}"
end

, , . .

FYI, .

-! !

0

All Articles