【问题标题】:Ansible replace ip address using regex by looping through a file line by lineAnsible通过逐行循环文件来使用正则表达式替换IP地址
【发布时间】:2019-09-29 11:55:39
【问题描述】:

我是 ansible 的新手。

我有一个包含多行的文件,其中某些行引用了 ipv4 地址。我的用例是用相同 ip 的递增版本替换每一行中的 ipaddress。

因此,例如,如果我的文件具有以下行:

一行的ip地址是10.1.1.1,用户名test1

一行的ip地址是20.2.2.2,用户名是test2

我想将其替换为:

一行的ip地址是10.1.1.2,用户名test1

一行的ip地址是20.2.2.3,用户名是test2

我正在使用 Ansible 替换模块在使用正则表达式的行中查找 ipv4 地址并替换。

- name: Increment and Replace Ip address and
      replace:
        path: "config/changed-ip.txt"
        regexp: "{{ '([0-9]{1,3}[\\.]){3}[0-9]{1,3}' }}"
        replace: "{{ 'x.x.x.x' }}"

以上代码将所有ip地址替换为我在replace中指定的地址

有没有办法从每一行中提取 ip 地址并将其递增并使用 lineinfile 或 replace 等任何模块替换 ipaddr 代替旧 ip?

我正在运行 ansible 2.6

【问题讨论】:

  • 您正在尝试增加正则表达式中捕获的整数。仅使用正则表达式是不可能的。您可以通过一堆任务在 ansible 中实现这一点,但这将非常冗长,对于下一个开发者来说可能难以理解并且维护起来非常痛苦。我建议您只需编写一个脚本并从 ansible 复制/执行它。如果您仍需要完整的 ansible 解决方案,请编写自定义 module 和/或 filter

标签: regex ansible


【解决方案1】:

尝试使用这个正则表达式:

^(\d{1,3}\.){3}\d{1,3}

^ 表示字符串的开头。

【讨论】:

  • 只是正则表达式不是问题。我想弄清楚如何逐行遍历文件,使用正则表达式提取 ip,然后用它的增量版本替换它
【解决方案2】:

您可以从 ansible playbook 调用 python 脚本来执行您感兴趣的任务。如果您想进行 IP 地址算术,ipaddress module 很有用。

例如:

---
  - hosts: all
    tasks:
    - command: "python3 process_ip_addresses.py text"

附带的python是:

from ipaddress import IPv4Address
import re
import sys

file_path = sys.argv[1]
with open(file_path) as f:
    text = f.read()

ip_addresses = re.findall( r'[0-9]+(?:\.[0-9]+){3}', text )
replacement_ip_addresses = [str(IPv4Address(address) + 1) for address in ip_addresses]
for old_address, new_addresss in zip(ip_addresses, replacement_ip_addresses):
    text = text.replace(old_address, new_addresss)

with open(file_path, "w") as f:
    f.write(text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2022-10-04
    • 2014-08-27
    • 2021-02-10
    • 2015-02-21
    • 2011-01-27
    • 2019-02-28
    相关资源
    最近更新 更多