Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Chef only_if not_if

Tags:

chef-infra

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!

like image 604
a.m. Avatar asked Dec 05 '11 22:12

a.m.


2 Answers

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

like image 132
Darrin Holst Avatar answered Oct 12 '22 18:10

Darrin Holst


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.

like image 45
Brad Knowles Avatar answered Oct 12 '22 18:10

Brad Knowles