a.m.
a.m.

Reputation: 2208

Understanding Chef only_if not_if

Im not sure I understand Chef conditional execution.

I'd like to do some conditional execution based on whether or not a database exists in Postgresql

So here's my example

execute "add_db" do
  cwd "/tmp"
  user "dbuser"
  command "createdb -T template_postgis mydb"
  not_if 'psql --list|grep mydb'
end

Running psql --list|grep mydb return what you would expect if the db exists (the line with the dbname entry) and nothing at all if it doesnt.

So how does not_if only evaluate that? True or false? 1 or 0? Dont all processes return 0 if they are successful?

Anywho any advice would be greatly appreciated!

Upvotes: 29

Views: 35390

Answers (2)

Darrin Holst
Darrin Holst

Reputation: 706

I just ran into this issue. My problem was that the not_if command was being run as 'root', not 'dbuser'. If you change it to

not_if 'psql --list|grep mydb', :user => 'dbuser'

then you may get the results you were looking for.

http://tickets.opscode.com/browse/CHEF-438

Upvotes: 24

Brad Knowles
Brad Knowles

Reputation: 211

Run the test for yourself, from the command line, and take a look at the default return value (a.k.a., "$?"). You should get something like this:

    % psql --list|grep mydb
    mydb-is-here
    % echo $?
    0

If you try something that is not there, you should get something like this:

    % psql --list|grep mydb-not-here
    % echo $?
    1

What chef is going to be looking at is the numeric value that would get stuffed into $?, i.e., either a "0" or a "1". In other words, your example you show for the "not_if" syntax is correct.

Upvotes: 21

Related Questions