Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible conditional based on contents of file

Tags:

python

ansible

Gratefully if someone could point out what's wrong with this…

The following code is meant to setup a test in the register module that prints the current value of /etc/timezone. There's then a task that compares that to the group/host {{ timezone }} variable and only runs the task if it's different (i.e. doesn't call handlers unnecessarily).

But it always runs regardless.

- name: check current timezone
  shell: cat /etc/timezone
  register: get_timezone

- name: set /etc/timezone
  shell: echo "{{ timezone }}" > /etc/timezone
  when: get_timezone.stdout.find('{{ timezone }}') == false
  notify: update tzdata

....

in group_vars/all.yml:

timezone: Europe/London
like image 504
William Turrell Avatar asked Apr 20 '14 13:04

William Turrell


1 Answers

Python string.find method returns -1 if it can't find the substring (https://docs.python.org/2/library/string.html, see string.find). So, you could modify your yml like that:

- name: set /etc/timezone
  shell: echo "{{ timezone }}" > /etc/timezone
  when: get_timezone.stdout.find('{{ timezone }}') == -1
  notify: update tzdata

or just use "not in":

- name: set /etc/timezone
  shell: echo "{{ timezone }}" > /etc/timezone
  when: '"{{ timezone }}" not in get_timezone.stdout'
  notify: update tzdata
like image 81
psl Avatar answered Sep 18 '22 14:09

psl