我如何 select 使用我的 ansible 剧本中的事实的变量?

How do I select a variable using a fact in my ansible playbook?

我想 select 根据实例的 aws 区域和可用区选择不同的选项。 作为一个非常简单的例子,我想根据地区将实例的时区设置为正确的时区。

我可以从 ohai_ec2 事实中获取区域和可用区。

如何使用变量列表中的事实 select?

我尝试直接引用变量,这适用于 when 语句,例如

when: ohai_ec2.region == "us-east-1"

我尝试了 Create Variable From Ansible Facts 中的查找,但格式不正确。

这个有效

# find the region
          - name: Base - find the region
            debug:
              msg: "Region is {{ ohai_ec2.region }} and zone is {{ ohai_ec2.availability_zone }}"

#Task: Base - Sets the timezone
          - name: Base - Set timezone to US East
            when: ohai_ec2.region == "us-east-1"
            timezone:
              name: US/Eastern
          - name: Base - Set timezone to CEST
            when: ohai_ec2.region == "eu-central-1"
            timezone:
              name: Europe/Madrid
          - name: Base - Set timezone to US West
            when: ohai_ec2.region == "us-west-2"
            timezone:
              name: US/Pacific

但这不是

...
        vars:
          mytz:
            us-east-1: "US/Eastern"
            us-west-2: "US/Pacific"
            eu-central-1: "Europe/Madrid"
...

          - name: Base - Set timezone to US East
            timezone:
              name: "{{ lookup ('vars', 'mytz'.'[ohai_ec2.region]') }}"

也不

          - name: Base - Set timezone to US East
            timezone:
              name: "{{ mytz.'[ohai_ec2.region]' }}"

我得到这个结果

fatal: [xxxxxxxxxx-xxxx]: FAILED! => {"msg": "template error while templating string: expected name or number. String: {{ mytz.[ohai_ec2.region] }}"}

使用事实和变量的正确方法是什么?

如果您有一个名为 mytz 的字典(您这样做),并且您有一个带有 region 键的字典 ohai_ec2,您可以使用该键的值来select 来自 mytz 的值,如下所示:

{{ mytz[ohai_ec2.region] }}

这是一个可运行的例子:

---
- hosts: localhost
  gather_facts: false
  vars:
    mytz:
      us-east-1: "US/Eastern"
      us-west-2: "US/Pacific"
      eu-central-1: "Europe/Madrid"
    ohai_ec2:
      region: us-east-1

  tasks:
    - name: Base - Set timezone to US East
      timezone:
        name: "{{ mytz[ohai_ec2.region] }}"