Ask Your Question

Using MySQL query within Exec's onlyif or unless

asked 2014-06-20 09:45:01 -0600

I have the following in my manifest file:

exec { "mysql table update domain_com":
    # Template uses $root_password
    command => template("ryse_mysql/domain_com.erb"),
    unless => "mysql --user=root --password=$root_password --database=domain_com --execute=\"SELECT * FROM wp_site WHERE domain = '';\"",

It should run my command (several MySQL queries) unless the query in unless returns a result. In other words, if the database does not exist or a particular row does not contain the data I need, my command should be executed.

The problem is that my command doesn't get fired. I previously had unless set to onlyif, but then it ran all the time. Any thoughts on why this isn't working (does it not return an exit code?) or is there another way of accomplishing this?

edit retag flag offensive close merge delete



you should launch the command manually on the machine and check the return code to see if it returns 0 or 1 when you need it to.

doc75 gravatar imagedoc75 ( 2014-06-23 05:53:33 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2014-06-23 11:59:46 -0600

I did some more troubleshooting and mysql does return an exit status of either 0 or 1 depending on success, however, success is only determined based on whether the query was actually able to run.

If, for example, the database doesn't exist, the user doesn't have access to make that query, or the query was malformed, you'd get an exit status of 1, but if the query was successful, whether it returned data or not (which is something I did care about), it would always return 0.

I ended up creating a small shell script as follows:


result=$(mysql --user=root --password=$1 --database=$2 --execute="SELECT * FROM $3 WHERE $4 = '$5';")

if [ $? -eq 0 ] && [ "$result" ]; then
    echo 'Target record EXISTS.'
    exit 0
    echo 'Target record DOES NOT EXIST.'
    exit 1

It basically checks whether mysql returns 0 or 1, but it also checks whether there was actually any data returned. If data was returned, it was all-in-all successful, but if either of them failed, it was not, at which point my other queries would run.

The final Puppet exec then looks something like this:

exec { "mysql table update domain_com":
    # Template uses $root_password
    command => template("ryse_mysql/domain_com.erb"),
    # Args: MySQL password, database, table, column, value
    unless => "/opt/scripts/ $root_password domain_com wp_site domain",

This did the trick for me.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools



Asked: 2014-06-20 09:45:01 -0600

Seen: 2,458 times

Last updated: Jun 23 '14