Daniel Gray
Daniel Gray

Reputation: 1792

Check environment variable in Chef only-if guard

I am trying to add a conditional guard to a Chef recipe action, so that it only runs if a certain environment variable is set (CLEAN_DB).

execute "create databases" do
    Chef::Log.info("Cleaning/creating the database")
    command "psql --file #{node['sql-directory']}/sql/db_create.sql"
    cwd node['sql-directory']
    action :run
    user node['postgresql-user']
    only-if (ENV['CLEAN_DB'] == "create")
end

The line right before the end is giving me trouble. It gives the following syntax error:

...
SyntaxError
-----------
/home/centos/.jenkins/workspace/test1__Deploy/cache/cookbooks/recipes/app_linux.rb:157: syntax error, unexpected end-of-input, expecting keyword_end
...

I've tried all the following:

only-if ENV['CLEAN_DB'] == "create"
only-if { ENV['CLEAN_DB'] == "create" }
only-if '("#{ENV[\'CLEAN_DB\']}" == "create")'
only-if 'if [[ "$CLEAN_DB" == "create" ]] ; then echo 0 ; else echo 1; fi;'
only-if 'if [[ "$CLEAN_DB" == "create" ]] ; then echo 0 ; else echo 1; fi'

And none of them seem to work. The documentation (https://docs.chef.io/resource_common.html) seems to suggest that all I need is a shell script that outputs 0 (in the shell case, it gives an error about a string literal in the condition) or a Ruby block (shown in the examples between {}). I am out of ideas at this point.

Upvotes: 1

Views: 2880

Answers (1)

StephenKing
StephenKing

Reputation: 37600

If you would have correctly spelled it only_if, then you should at least have succeeded with the second try (of the last block).

The correct syntax would be:

execute "create databases" do
    # Logging here makes IIRC no sense because it's emitted at compile time
    # Chef::Log.info("Cleaning/creating the database")
    command "psql --file #{node['sql-directory']}/sql/db_create.sql"
    cwd node['sql-directory']
    action :run
    user node['postgresql-user']
    only_if { ENV['CLEAN_DB'] == "create" }
end

Alternatively, you can use

    only_if do ENV['CLEAN_DB'] == "create" end

Upvotes: 3

Related Questions