如何在ansible中遍历文本文件的每一行

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

我必须遍历包列表文件,其中包含包列表及其体系结构。如何将这些输入提供给我的剧本文件?我找到了一种单独获取包名称的方法,但体系结构版本没有出现。这是我的 package_list 文件

nginx | x86_64
telnet| x86_64
openssh | i386

这是我的剧本

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

如有任何帮助,我们将不胜感激

所需的输出是包名,架构应该通过ansible-playbookpackages.txt文件读取

试试这个剧本:

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

结果:

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

您的情况:

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

按照ansible的版本你也可以写line: "{{ item | split('|') | list }}"

您需要通过过滤将行拆分为必要的值。

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

更多文档

进一步问答