user3423536
user3423536

Reputation: 87

Build Ansible dictionary from stdout

I am creating Ansible roles to install various software. Within these roles, I'm using ansible_pkg_mgr to determine whether I have to use apt or yum. This works as expected.

When retrieving certain repositories like https://download.docker.com/linux/centos/7/x86_64/stable/repodata/ I want to use lsbs_release -a to obtain values needed in order to correctly populate the URL for the specific release.

The code below works but how would I loop to the end of the list and put the key/value pairs in a dictionary?

I'm always open to other suggestions or if there's a cleaner method. I'm not necessarily stuck and would appreciate another set of eyes. I think it's a good problem to solve as it'll be useful for future projects.

- hosts: localhost
  connection: local

  tasks:
  
  - name: check OS
    command: lsb_release -a
    register: var

  - name:
    set_fact: 
      foo: "{{ var.stdout }}"

  - name:
    set_fact:
      bar: "{{ foo.split('\n') | replace('\\t','') }}"

  - name:
    set_fact:
      lsbs_release_attributes:
        - key: "{{ bar[0].split(':',1)[0] }}"
        - value: "{{ bar[0].split(':',1)[1] }}"```

Upvotes: 1

Views: 271

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68004

Q: "How would I loop to the end of the list and put the key/value pairs in a dictionary?"

A: Try

  - set_fact:
      lsbs_release_attributes: "{{ lsbs_release_attributes|d({})|
                                   combine({key: val}) }}"
    loop: "{{ bar }}"
    vars:
      _item: "{{ item.split(':',1) }}"
      key: "{{ _item.0 }}"
      val: "{{ _item.1 }}"

Upvotes: 1

Related Questions