基于文件内容的Ansible条件
如果有人能指出这段代码有什么问题,我会非常感激……
以下代码是为了在注册模块中设置一个测试,目的是打印当前的 /etc/timezone
的值。接下来有一个任务,它会把这个值和组/主机的 {{ timezone }} 变量进行比较,只有在这两个值不一样的时候才会执行这个任务(也就是说,不会不必要地调用处理程序)。
但是无论如何,这个任务总是会执行。
- 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
....
在 group_vars/all.yml 文件中:
timezone: Europe/London
1 个回答
18
Python中的string.find方法如果找不到你要的子字符串,就会返回-1(详细信息可以查看这里)。所以,你可以这样修改你的yml文件:
- name: set /etc/timezone
shell: echo "{{ timezone }}" > /etc/timezone
when: get_timezone.stdout.find('{{ timezone }}') == -1
notify: update tzdata
或者你也可以直接用“not in”来判断:
- name: set /etc/timezone
shell: echo "{{ timezone }}" > /etc/timezone
when: '"{{ timezone }}" not in get_timezone.stdout'
notify: update tzdata