Ansible:将String与寄存器进行比较

时间:2017-07-20 16:29:58

标签: ansible

此脚本旨在获取每个服务器上的时区并将其存储在寄存器中。之后,我将存储在寄存器中的时区与变量time_zone进行比较,以查看所有服务器是否都在PDT时间内。第二个任务应该打印出所有不在PDT时间内的服务器,但逻辑与我的意图完全相反。目前,第二个任务在TZ!= PDT时运行,在TZ == PDT时跳过。我在本地运行,目前我在PDT时区。

---
- hosts: localhost
  gather_facts: no

  vars:
    time_zone: 'PDT'

  tasks:

  - name: Find the servers that are not in PDT time zone.
    shell: date | awk '{print $5}'
    register: TZ
  - debug: msg={{TZ.stdout}}

  - name: Display the servers that are not in PDT time zone. 
    shell: echo $HOSTNAME
    when: TZ != time_zone

2 个答案:

答案 0 :(得分:2)

当内置方法可用时,请避免使用shell

---
- hosts: localhost
  vars:
    time_zone: 'PDT'
  tasks:
    - name: Display the servers that are not in PDT time zone. 
      debug:
        msg: "{{ ansible_hostname }}"
      when: ansible_date_time.tz != time_zone

答案 1 :(得分:0)

如果我正确理解所需的逻辑,您只需在条件内使用已注册变量的标准输出。

- name: Display the servers that are not in PDT time zone. 
  shell: echo $HOSTNAME
  when: TZ.stdout != time_zone