ansible - Access value in nested data structure

Viewed 38

I'm quite new to ansible and automation / scripting in general. I've the following nested data structure stored as a variable in the group_vars:

data_shares:
   share_data_1:
        nfs_data_host: 'x.x.x.x'
        directory: '/mount/nfs-share1'
        share: '/data-fs/nfs-share1'
        nfs_fstype: 'nfs4'
        nfs_opts: 'rw,hard,proto=tcp,timeo=600,retrans=0,sec=sys'
   share_data_2:
        nfs_data_host: 'x.x.x.x'
        directory: '/mount/nfs-share2'
        share: '/data-fs/nfs-share2'
        nfs_fstype: 'nfs4'
        nfs_opts: 'rw,hard,proto=tcp,timeo=600,retrans=0,sec=sys'
   share_data_3:
        nfs_data_host: 'x.x.x.x'
        directory: '/mount/nfs-share3'
        share: '/data-fs/nfs-share3'
        nfs_fstype: 'nfs4'
        nfs_opts: 'rw,hard,proto=tcp,timeo=600,retrans=0,sec=sys'

Cannot even say if it's a nested list or dictionary, please excuse.

Let's say that I want to provide the "directory" value and other values of the sub section "share_data_3" as variables for the following tasks:

- name: Create mount point, mount data share 3
  block:
    - name: Create mount point data share 3
      ansible.builtin.file:
        path: '{{ share_data_3.value.directory }}'
        state: directory
        owner: root
        group: root
        mode:  '0644'
      when: ansible_facts.mounts | selectattr('mount', '==', '/mount/nfs-share3') | length == 0


    - name: Mount data share 3 
      ansible.posix.mount: 
        src: '{{ share_data_3.value.nfs_data_host }}:{{ share_data_3.value.share }}'
        path: '{{ share_data_3.value.share }}'
        opts: '{{ share_data_3.value.nfs_opts }}'
        state:  mounted
        fstype: '{{ share_data_3.value.nfs_fstype }}'
      when: ansible_facts.mounts | selectattr('mount', '==', '/mount/nfs-share3') | length == 0 

But I receive a fatal error, indicating that 'dict object' has no attribute 'directory' and so on. Also when i try '{{ data_shares.share_data_3.value.directory }}' for exmple it keeps failing.

Any suggestions? I've tried to check the ansible documentation, but it is somehow difficult for me to understand, as the whole data structure topic is new for me.

Many Thanks in advance for some tips.

0 Answers
Related