how do fire handler with condition?

Hi

I want to fire handler with condition.
for example, when change httpd.conf, i want to restart apache on staging, bun not want on production.

what should i do?

inventory/staging
httpd_restart=true

inventory/production
httpd_restart=false

tasks:
# i want to fire when inventory is staging
# but not fire when inventory is production
- copy: src=httpd.conf dest=/etc/httpd/httpd.conf
handler:
- service name=httpd state=restart

thanks.

It's a tricky one - you probably don't want production bouncing
services all day long
but on the other hand I doubt you never want to pick up any config
changes either.

One day you'll have a power outage or something and that's a bad time
to find out your
configuration file is actually invalid.

That said, we do occasionally do this against prod. if we've tested in
other envs and really
do need to avoid a restart.

( A good example would be something we can dynamically add to a
service configuration by
hand at runtime without a restart, but we also want to ensure the
on-disk config is up to date).

If we don't want a service to bounce we

* do a 'dummy run' of ansible (-C) with the -D (diff) option
* see what Ansible would change
* make those changes by hand

that way the handlers don't fire, since Ansible didn't change the
files contents.

This is a hassle, but since we don't want to encourage this behaviour
that's fine :slight_smile:

We have this requirement as well. We just put a when condition on the task in the handler to only restart the service if it’s not prod. You need to have the environment in a variable for this to work. e.g. this may not be the 100% correct syntax as I’m not at work, but we do something like:

handler:

  • service: name=httpd start=restarted
    when: {{environment}} != ‘prod’

when: "'{{environment}}' != 'prod'"

also i would not use environment as a variable as it can conflict with
the keyword.

actually, let me correct myself, no mustaches needed in when:

when: environment != 'prod'

Agreed, “environment” is probably a bad choice of variable names. We actually use a variable called “node_environment”.

hi.

thaks for many answer.

i feel ugly a little for use ‘when’ (thanks Paul),
and feel tricky to fire handler with condition (thanks Dick).

i decide to restart service all enviroments.

thanks.

2015年8月5日水曜日 22時27分57秒 UTC+9 Ichiro MATSUNAGA: