Home > other >  how to traverse through each line of a text file in ansible
how to traverse through each line of a text file in ansible

Time:03-22

I have to traverse through package list file which contains list of packages with their architecture. How can I feed those input to my playbook file? I found a way to get the package names alone but architecture version is not coming. This is my package_list file

nginx | x86_64
telnet| x86_64
openssh | i386

This is my playbook

 - name: get contents of package.txt
   command: cat "/root/packages.txt"
   register: _packages
 - name: get contents of architecture from packages.txt
   command: cat "/root/packages.txt" | awk '{print $3}'
   register: _arch

 - name: Filter
   theforeman.foreman.content_view_filter:
     username: "admin"
     password: "mypass"
     server_url: "myhost"
     name: "myfilter"
     organization: "COT"
     content_view: "M_view"
     filter_type: "rpm"
     architecture: "{{ _arch }}"
     package_name: "{{ item }}"
     inclusion: True
   loop: "{{ _packages.stdout_lines }}"
   loop: "{{ _arch.stdout_lines }}"

Any help would be appreciated

The required output is package name and architecture should be read from packages.txt file through ansible-playbook

CodePudding user response:

try this playbook:

- name: Reproduce issue
  hosts: localhost
  gather_facts: no
  tasks:
    - name: get contents of package.txt
      command: cat "/root/packages.txt"
      register: _packages
    - debug: 
        msg: "package: {{ line.0 }}, arch: {{ line.1 }}"         
      loop: "{{ _packages.stdout_lines }}"
      vars:
        line: "{{ item.split('|')|list }}"

result:

ok: [localhost] => (item=nginx | x86_64) => {
    "msg": "package: nginx , arch:  x86_64 "
}
ok: [localhost] => (item=telnet| x86_64) => {
    "msg": "package: telnet, arch:  x86_64 "
}
ok: [localhost] => (item=openssh | i386) => {
    "msg": "package: openssh , arch:  i386 "
}

for your case:

 - name: Filter
   theforeman.foreman.content_view_filter:
     :
     :
     architecture: "{{ line.1 }}"
     package_name: "{{ line.0 }}"
     inclusion: True
   loop: "{{ _packages.stdout_lines }}"
   vars:
     line: "{{ item.split('|')|list }}"

following the version of ansible you could write too line: "{{ item | split('|') | list }}"

CodePudding user response:

You need to split up the line into the necessary values by filtering.

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Gahter package list
    shell:
      cmd: cat package.txt
    register: _packages

  - name: Show packages
    debug:
      msg: "Name: {{ item.split('|')[0] }}, Arch: {{ item.split('|')[1] }}"
    loop: "{{ _packages.stdout_lines }}"

Further Documentation

Further Q&A

  • Related