Hostname usually look like vcs-200-01. So when ever the hostname has vcs or vhs task should be run. I have tried below task but its running on all VMs instead of running on specific Vms
- name:Exceute shell script
become:yes
become_user:root
become_method:sudo
command: sh /usr/..../example.sh
when:("'vcs' in inventory_hostname_short") or ("'vhs' in inventory_hostname_short")
The problem is the quotation of the logical expressions inside the parenthesis. These expressions are not evaluated but taken as strings. A not empty string evaluates to True . This is the reason the condition is always True .
when: ("'vcs' in inventory_hostname_short") or
("'vhs' in inventory_hostname_short")
The solution is simple. Remove the quotation. For example the task
- debug:
var: inventory_hostname_short
when: ('vcs' in inventory_hostname_short) or
('vhs' in inventory_hostname_short)
and the inventory
shell> cat hosts
vcs-200-01
vhs-200-01
vxs-200-01
give
ok: [vcs-200-01] =>
inventory_hostname_short: vcs-200-01
ok: [vhs-200-01] =>
inventory_hostname_short: vhs-200-01
skipping: [vxs-200-01]
when: 'vcs' in inventory_hostname_short
when: ('vcs' in inventory_hostname_short) # OK
The recommended quotation fixes the problem
when: ("'vcs' in inventory_hostname_short") # WRONG
so does also the closing in parenthesis
when: ('vcs' in inventory_hostname_short) # OK
but not both parenthesis and quotation
when: ("'vcs' in inventory_hostname_short") # WRONG
The or expression
when: "'vcs' in inventory_hostname_short" or
"'vhs' in inventory_hostname_short"
will produce a similar error and the same recommendation
when: ('vcs' in inventory_hostname_short) or
('vhs' in inventory_hostname_short)
But here the recommended solution will not work and will produce the same error and the same recommendation
when: "('vcs' in inventory_hostname_short) or
('vhs' in inventory_hostname_short)"
The logical expressions in or must be closed in parenthesis
when: ('vcs' in inventory_hostname_short) or ('vhs' in inventory_hostname_short)
Then the condition may be optionally quoted
when: "('vcs' in inventory_hostname_short) or ('vhs' in inventory_hostname_short)"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.