0
votes

I'm new to Ansible and trying to get a service state where the service name is dynamic and set by set_fact before in the playbook.

How can you build a variable within another variable? I wish I could use something like that to display my service state :

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

But well it doesn't work.

So I tried this way with 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 }}"

I got the following error :

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"}

When the following works just fine :

  - name: print service state
    debug:
      msg: "{{ ansible_facts.services['myservice'].state }}"
1
{{ ansible_facts.services[servicename].state }} - Zeitounator
Thank you so much! It works, I spent hours on this when it was this obvious. - user123165

1 Answers

1
votes

Inside a {{ … }} block, you can access the variables directly. And from my point of view, you can leave the ansible_facts out, as well as the variable assignment in the second task.

This will do what you want (and as Zeitounator already wrote):

- 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 }}"