基于文件内容的Ansible条件

Wil*_*ell 6 python 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
Run Code Online (Sandbox Code Playgroud)

....

在group_vars/all.yml中:

timezone: Europe/London
Run Code Online (Sandbox Code Playgroud)

psl*_*psl 14

Python string.find方法如果找不到子字符串则返回-1(https://docs.python.org/2/library/string.html,请参阅string.find).所以,你可以修改你的yml:

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

或者只是使用"不在":

- name: set /etc/timezone
  shell: echo "{{ timezone }}" > /etc/timezone
  when: '"{{ timezone }}" not in get_timezone.stdout'
  notify: update tzdata
Run Code Online (Sandbox Code Playgroud)