如何使用 Ansible 在远程文件中搜索字符串?

2024-04-09

基于一个问题

  • 如何使用 Ansible 在文件中搜索字符串? https://superuser.com/a/1764857/754490
  • Ansible:如何从文件内容中提取特定字符串? https://stackoverflow.com/a/75099369/6771046
  • Can slurp用作直接替代lookup? https://stackoverflow.com/a/73711588/6771046

以及诸如此类的考虑

  • 通过使用slurp模块一将通过网络将整个文件从远程节点传输到控制节点,以便处理它并查找字符串。对于日志文件,这些文件可以是几 MB,并且如果远程节点上的文件包含特定字符串,那么人们主要只对信息感兴趣,因此人们只需要传输这种信息,true or false.
  • 如何使用 Ansible 在远程节点上执行脚本? https://stackoverflow.com/a/73363872/6771046

我想知道如何解决这个问题而不是使用shell module?

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

  vars:

    SEARCH_STRING: "test"
    SEARCH_FILE: "test.file"

  tasks:

  - name: Search for string in file
    command:
      cmd: "grep '{{ SEARCH_STRING }}' {{ SEARCH_FILE }}"
    register: result
    # Since it is a reporting task
    # which needs to deliver a result in any case
    failed_when: result.rc != 0 and result.rc != 1
    check_mode: false
    changed_when: false

或者不使用解决方法lineinfile module?

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

  vars:

    SEARCH_STRING: "test"
    SEARCH_FILE: "test.file"

  tasks:

  - name: Search for string
    lineinfile:
      path: "{{ SEARCH_FILE }}"
      regexp: "{{ SEARCH_STRING }}"
      line: "SEARCH_STRING FOUND"
      state: present
    register: result
    # Since it is a reporting task
    changed_when: false
    failed_when: "'replaced' not in result.msg" # as it means SEARCH_STRING NOT FOUND
    check_mode: true # to prevent changes and to do a dry-run only

  - name: Show result, if not found
    debug:
      var: result
    when: "'added' in result.msg" # as it means SEARCH_STRING NOT FOUND

由于我正在寻找一种更通用的方法,这是否是一个可行的案例您应该开发一个模块吗? https://docs.ansible.com/ansible/latest/dev_guide/developing_modules.html


下列的开发模块 https://docs.ansible.com/ansible/latest/dev_guide/developing_modules_general.html and 创建模块 https://docs.ansible.com/ansible/latest/dev_guide/developing_modules_general.html#creating-a-module我找到了以下简单的解决方案

定制模块library/pygrep.py

#!/usr/bin/python

from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from ansible.module_utils.basic import AnsibleModule

def run_module():
    module_args = dict(
        path=dict(type='str', required=True),
        search_string=dict(type='str', required=True)
    )

    result = dict(
        changed=False,
        found_lines='',
        found=False
    )

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True
    )

    with open(module.params['path'], 'r') as f:
        for line in f.readlines():
            if module.params['search_string'] in line:
                result['found_lines'] =  result['found_lines'] + line
                result['found'] = True

    result['changed'] = False

    module.exit_json(**result)

def main():
    run_module()

if __name__ == '__main__':
    main()

剧本pygrep.yml

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

  vars:

    SEARCH_FILE: "test.file"
    SEARCH_STRING: "test"

  tasks:

  - name: Grep string from file
    pygrep:
      path: "{{ SEARCH_FILE }}"
      search_string: "{{ SEARCH_STRING }}"
    register: search

  - name: Show search
    debug:
      var: search
    when: search.found

对于一个简单的test.file

NOTEST
This is a test file.
It contains several test lines.
321tset
123test
cbatset
abctest
testabc
test123
END OF TEST

它将导致输出

TASK [Show search] ******************
ok: [localhost] =>
  search:
    changed: false
    failed: false
    found: true
    found_lines: |-
      This is a test file.
      It contains several test lines.
      123test
      abctest
      testabc
      test123

一些链接

  • 是什么grepPython 中的等效项? https://stackoverflow.com/a/47977225/6771046
  • cat, grep and cut- 翻译成Python https://stackoverflow.com/a/26659479/6771046
  • 相当于Linux命令的Python代码是什么grep -A? https://stackoverflow.com/a/50096658/6771046
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Ansible 在远程文件中搜索字符串? 的相关文章

随机推荐

  • 如何通过流java8中的键获取所有不同的值

    我目前正在学习一些关于流的知识 我有以下 JSONArray 并且我希望能够检索所有不同的 xvalue datasets ds1 xvalues empty x1 x2 ds2 xvalues empty x1 x2 x3 我正在尝试以下
  • 如何正确构建我的 HTML 文件?

    对于一个基本的静态网站 有几个页面和子页面 我对 HTML 页面目录结构的最佳实践有点困惑 假设我有一个像这样的简单网站 索引 主页 页面 关于页面 联系页面和新闻页面 在新闻页面上 有两个链接指向新闻页面的两个子页面fizz html和b
  • 为什么Python函数有一个__dict__?

    在Python中 使用创建的函数def and lambda have a dict 属性 以便您可以动态地向它们添加属性 有一个 dict 每个函数都有内存成本 一个空的dictPython 2 6 中使用 140 个字节 向函数添加属性
  • 在 vb.net 中纠正图像方向服务器端

    在我正在开发的移动网络应用程序中 用户可以使用相机拍照 并将相机图像上传到服务器 我遇到的问题是 在 iOS 设备上 图像会获得与其关联的 EXIF 方向标签 例如 ROTATE 90 CW 该方向标签会导致图像在显示时以不正确的方向显示
  • Django与领域和自身的多对多关系独特

    我尝试使用语言和内容创建帖子 并将其与同一页面的其他版本相关联 但我陷入困境 class Page models Model content models TextField language models CharField max le
  • 如何在android中使用用户当前位置获取邮政编码

    我正在尝试获取邮政编码 但无法获取邮政编码 邮政编码 我可以获取当前城市 但是当我尝试获取邮政编码时 它给了我一个空指针异常 谁能帮我 final Geocoder gcd new Geocoder getApplicationContex
  • 字符的序数/int/ascii 值

    在 clojure repl 中我可以这样做 gt int a 97 在闭包脚本中 我不断得到 gt int a 0 在我当前的 clojurescript 项目中 我定义了一个 var def ord a int a 当我检查发出的 ja
  • C:将值扫描到数组中与常量的相等性进行比较的问题[关闭]

    Closed 这个问题是无法重现或由拼写错误引起 help closed questions 目前不接受答案 我对 C 完全陌生 现在我正在尝试掌握基础知识 但在从 scanf 读取数据和填充数组时遇到问题 根据我的观察 我认为问题出在 s
  • 有没有办法在android 2.1中不使用动画来旋转按钮

    我正在寻找旋转按钮的方法 不使用动画 我不想使用动画 因为this https stackoverflow com questions 8037185 onlclick listener is not working properly 如果
  • 如何向这个 elm 效果示例添加第二个骰子?

    我是 Elm 新手 一直在查看以下示例 请注意 这是在较新的 0 17 架构下 其中 Action 现在是 Command http elm lang org examples random http elm lang org exampl
  • mysql查询失败时是否有错误日志记录?

    我很好奇当我执行查询时 MySQL 数据库是否记录任何错误 我知道我打电话mysql 错误 http php net manual en function mysql error php检索错误 但数据库端是否还有其他日志记录 默认情况下
  • 用于数据库备份的Linux shell脚本

    我尝试了很多数据库备份脚本 但我无法成功 我想每小时备份一次数据库 我将文件添加到 etc cron hourly 文件夹 将其 chmod 更改为 755 但它没有运行 至少我写了我的伪代码 如果您能为该操作编写一个脚本并告诉我我还应该做
  • 为jade文件中的变量赋值

    是否可以在jade文件中分配变量 以使代码更具可读性 具体来说 我创建了这个jade文件 extends layout var format 1 0f block title title Your score table block bod
  • 如何声明依赖关系

    我正在研究 Dagger 2 所以我想了解一些基本的东西 我有以下代码 Module public class MainModule Provides public Presenter provideMainActivityPresente
  • 在头文件中声明 extern 结构模板以在 c 文件中全局使用

    我的目标是声明和定义一个结构template在我的头文件中 然后我希望使用这个模板来声明和定义个人我的 c 文件中的结构 这是我的目标的一个粗略示例 头文件 include
  • 如何在 ruby​​ 中读取 INI 文件

    如何在 ruby 中读取 写入 ini 文件 我有一个需要的 ini 文件 read 更改条目 写出到不同的位置 我该如何在红宝石中做到这一点 关于这一点的文档是黯淡的 使用 InIFile Gem 正如 method所说 使用inifil
  • js中压缩一串0和1

    介绍 我目前正在用 js 开发 John Conway 的 Game of Life 我的游戏可以运行 在这里查看 http goljs github io GoL 我正在开发额外的功能 例如与您的朋友分享您的 网格 游戏 为此 我将网格的
  • 如何使用fastify-cors实现仅一个api跨域?

    我想让 POST 本地主机 产品 只是这个API可以跨域 我不知道该怎么做 fastify register require fastify cors origin methods POST 这是我的 API method POST url
  • 如何定义软件的版本号?

    确定软件或组件应使用的版本号的最佳方法是什么 设置版本号有通用规则吗 我很确定这是一个基本问题 但搜索一段时间后我没有找到任何有用的东西 微软有一个约定 major minor revision build 或关注Jeff 的版本控制系统
  • 如何使用 Ansible 在远程文件中搜索字符串?

    基于一个问题 如何使用 Ansible 在文件中搜索字符串 https superuser com a 1764857 754490 Ansible 如何从文件内容中提取特定字符串 https stackoverflow com a 750