Ansible:如何使用另一个变量获取动态服务状态

Ansible: how to get dynamic service state with a variable within another

我是 Ansible 的新手,正在尝试获取服务名称动态的服务状态,并在剧本中由 set_fact 设置。

如何在另一个变量中构建一个变量? 我希望我可以使用类似的东西来显示我的服务状态:

{{ ansible_facts.services['{{ servicename }}'].state }} 

但它不起作用。

所以我用 vars 尝试了这种方式:

  - name: set service name
    ansible.builtin.set_fact:
      servicename: "'myservice'"
    when: ansible_distribution_major_version == "7"

  - name: print service state
    debug: msg={{ vars['ansible_facts.services[' + servicename + '].state'] }}
    vars:
      servicename: "{{ servicename }}"

我收到以下错误:

fatal: [myhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute u\"ansible_facts.services['myservice'].state\"\n\nThe error appears to be in '/etc/ansible/playbook/myplaybook.yaml': line 20, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: print service state\n    ^ here\n"}

当以下工作正常时:

  - name: print service state
    debug:
      msg: "{{ ansible_facts.services['myservice'].state }}"

{{ … }} 块中,您可以直接访问变量。从我的角度来看,您可以将 ansible_facts 以及第二个任务中的变量赋值保留在外。

这会做你想做的(正如 Zeitounator 已经写的那样):

- hosts: localhost
  vars:
    services:
      myservice:
        state: foo
  tasks:
    - name: set service name
      ansible.builtin.set_fact:
        servicename: "myservice"

    - name: print service state
      debug:
        msg: "{{ services[servicename].state }}"