Accessing file content via ansible

file.txt

rpmname: version
rpmname: version

Playbook:-

  • hosts: all
    gather_facts: false

tasks:

  • name: store the value
    shell: cat /etc/ansible/playbooks/file.txt
    register: versions
  • name: Ansible Dictionary variable Example
    debug:
    msg: “rpmname is {{ item.key}} and value is {{item.value}}”

i want to access multiple key values in ansible -playbook to perform operation. looks like something is missing to access that values.

Hello ansible team can anyone suggest?

Where did 'item' come from? Usually, when you use a task in a loop, you can access the loop item via the variable 'item'. I don't see a loop in your playbook.

In your example, look at versions.stdout for file contents. Or use the Slurp module to read file contents.

Hi Sudheer,

Thats the problem now how should we iterate items.

[test@4c594b5b8054 playbooks]$ ansible-playbook -vv test3.yaml
ansible-playbook 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u’/home/test/.ansible/plugins/modules’, u’/usr/share/ansible/plugins/modules’]
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.5 (default, Jun 20 2019, 20:27:34) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
Using /etc/ansible/ansible.cfg as config file

PLAYBOOK: test3.yaml ********************************************************************************************
1 plays in test3.yaml

PLAY [all] ******************************************************************************************************
META: ran handlers

TASK [store the value] ******************************************************************************************
task path: /etc/ansible/playbooks/test3.yaml:5
changed: [127.0.0.1] => {“ansible_facts”: {“discovered_interpreter_python”: “/usr/bin/python”}, “changed”: true, “cmd”: “cat /etc/ansible/playbooks/file.txt”, “delta”: “0:00:01.326287”, “end”: “2019-07-11 12:33:51.894849”, “rc”: 0, “start”: “2019-07-11 12:33:50.568562”, “stderr”: “”, “stderr_lines”: , “stdout”: “httpd: 2.4\napache: 2.8”, “stdout_lines”: [“httpd: 2.4”, “apache: 2.8”]}

TASK [Ansible Dictionary variable Example] **********************************************************************
task path: /etc/ansible/playbooks/test3.yaml:8
fatal: [127.0.0.1]: FAILED! => {“msg”: “with_dict expects a dict”}

PLAY RECAP ******************************************************************************************************
127.0.0.1 : ok=1 changed=1 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0

in this example its required the content should be dictionary format.

But if you take vars in anisbleplaybook itself it will work because vars is in dict format.