如何在ansible中读取文件的特定部分

How to read a particular part of file in ansible

我有一个包含以下数据的文件

!

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

我只想从文件中读取添加命令。

使用查找插件我能够读取整个文件的数据。

但我不知道如何只从文件中读取特定的添加命令

这是我编写的代码。

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

我被困在这个问题上point.Could任何人都可以帮助我了解如何在 ansible 中读取文件的特定部分。

使用with_lines。下面的戏

- 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

给予

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