Ansible 2.3:单个正则表达式,用于替换文件中的多行

时间:2018-02-08 23:08:38

标签: python regex ansible ansible-2.x

试图找出正则表达式来替换文件中的下面多行

我要更新的目标文件

# enable the encryption , to be used .
 ssh_encryption_options:
    enabled: false
    optional: false
    algorithm: tls

我的任务定义

   - replace:
       path: /etc/config/
       regexp: '^(ssh_encryption_options:
     enabled: false)$'
       replace: '^(ssh_encryption_options:
     enabled: true)$'
     become: true

文件中的预期输出

ssh_encryption_options:
    enabled: true
    optional: false
    algorithm: tls

但是ansible无法在该文件中找到要替换的多行,在regex中给出。我确定之前有一个人尝试过这个场景。

1 个答案:

答案 0 :(得分:0)

  1. /etc/config/替换为您要更改的文件的路径;

  2. 注意空白(显式添加或使用\s进行匹配);

  3. 使用\n匹配换行符;

  4. 使用捕获组来简化替换值。

  5. - replace:
        path: /etc/config/_file_
        regexp: '^( ssh_encryption_options:\n\s*enabled: )false$'
        replace: '\1true'
      become: true