How to read a particular part of file in ansible

半世苍凉 提交于 2019-12-01 13:10:25

问题


I have a file which has the following data

!

multiply 4 and 5

multiply 5 and 6

!

add 3 to 4

add 8 to 4

!

sub 3 from 6

sub 9 from 5

!

!

div 6 by 2

div 8 by 1

I want to read only add commands from the file.

Using lookup plugin I was able to read the data of the entire file.

But I don't know how to read only the specific add commands from the file

Here's the code that I've written.

---
 - name: Extracting the Add commands from the File
   hosts: 127.0.0.1
   connection: local

   vars:
           contents: "{{lookup('file', 'file1.txt')}}"

   tasks:
           - name: Printing the Add commands of the File
             debug:
                     var: contents

I am stuck at this point.Could anyone help me out of how to read the specific part of a file in ansible.


回答1:


Use with_lines. The play below

- hosts: localhost
  vars:
    my_data_file: "{{ playbook_dir }}/data.txt"
    my_commands: []
  tasks:
    - set_fact:
        my_commands: "{{ my_commands + [ item ] }}"
      with_lines: "cat {{ my_data_file }}"
      when: item is search('^add')
    - debug:
        var: my_commands

gives

"my_commands": [
    "add 3 to 4", 
    "add 8 to 4"
]


来源:https://stackoverflow.com/questions/56562112/how-to-read-a-particular-part-of-file-in-ansible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!