Esegui attività solo se l'host non appartiene a un gruppo


106

Mi piacerebbe poter eseguire un'attività ansible solo se l'host del playbook corrente non appartiene a un determinato gruppo. In semi pseudo codice:

- name: my command
  command: echo stuff
  when: "if {{ ansible_hostname }} not in {{ ansible_current_groups }}"

Come dovrei farlo?

Risposte:


198

Ecco un altro modo per farlo:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_namesè una variabile magica come documentato qui: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

group_names è un elenco (array) di tutti i gruppi in cui si trova l'host corrente.


3
+1 e se non includi la citazione circostante ottieni l'errore:This one looks easy to fix. It seems that there is a value started with a quote, and the YAML parser is expecting to see the line ended with the same kind of quote.
Peter Ajtai

3
Trovo questo approccio più leggibile e comodo da scrivere, ma entrambi funzionano ugualmente bene. when: inventory_hostname not in groups.certain_groups
Liam

4
In questo modo è più robusto rispetto al inventory_hostname in groups['groupname']fatto che nei casi in cui lo stucco stesso non esiste, Ansible genererà un errore del tipo "Assicurati che il nome della tua variabile non contenga caratteri non validi come '-': l'argomento di tipo 'StrictUndefined' non è iterabile"
hamx0r

20

È possibile impostare una variabile di controllo nei file vars situati group_vars/o direttamente nel file hosts come questo:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2

Ed esegui attività come questa:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var

2
la risposta accettata è più accurata per la domanda, ma questo ti porta su una strada migliore
nik.shornikov,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.