【问题标题】:Ansible : use a fact variable with a dictionary variableAnsible:将事实变量与字典变量一起使用
【发布时间】:2020-11-26 18:14:32
【问题描述】:

我想在多台 linux 服务器上安装 Apache。 Apache 包在 RedHat 或 Debian 操作系统(apache2 vs httpd)上没有相同的名称:这是一种使用 ansible 事实变量(“ansible_os_family”)作为字典变量键的方法吗?

类似的东西(但这不起作用):

---
- name: playbook1
  hosts: all
  become: yes
  vars:
    apache_packages: {
      "RedHat": "httpd",
      "Debian": "apache2"
      }
  tasks:
    - name: Install Apache server
      package:
        name:  "{{ apache_packages['{{ ansible_os_family }}']  }}"
        state: present
...

【问题讨论】:

    标签: ansible ansible-facts


    【解决方案1】:

    将 Jinja 分隔符嵌套在另一个 Jinja 分隔符中绝不是一个好主意。

    另一条规则是“胡须不堆叠”。我们经常看到这样的:

    {{ somevar_{{other_var}} }}
    

    如果上述操作无法如您所愿, 您需要使用动态变量,请酌情使用以下内容:

    {{ hostvars[inventory_hostname]['somevar_' + other_var] }}
    

    对于“非主机变量”,您可以使用 vars lookup 插件:

    {{ lookup('vars', 'somevar_' + other_var) }}
    

    来源:https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#when-should-i-use-also-how-to-interpolate-variables-or-dynamic-variable-names

    如果你没有用引号括起来,它将被假定为一个变量,所以在这种情况下,这很简单:

    name:  "{{ apache_packages[ansible_os_family] }}"
    

    【讨论】:

      【解决方案2】:

      试试这个:您将包定义为列表的字典(基于 os 系列)

      - name: playbook1
        hosts: localhost
        become: yes
        vars:
          packages:
            debian:
              - apache2
            redhat:
              - httpd
        tasks:
          - name: Install Apache server
            package:
              name:  "{{ item }}"
              state: present
            loop: "{{ packages.get(ansible_os_family|lower) }}"
      

      【讨论】:

        【解决方案3】:

        我会做一些类似下面的事情来减少线条

        - hosts: localhost
          become: yes 
          tasks:
          - package:
              name: "{{ 'apache2' if ansible_os_family == 'Debian' else ('httpd' if ansible_os_family == 'RedHat') }}"
              state: present
        

        【讨论】:

          猜你喜欢
          • 2016-03-03
          • 1970-01-01
          • 2021-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多