首页 文章

使用Ansible替换匹配文件中的多个单词

提问于
浏览
1

该项目是更新许多服务器上的通配符证书路径,每个服务器都有一个名称不同的Vhost - * .conf文件 .

我想搜索与 V*.conf 匹配的文件,然后通过它们grep并替换 crtkeyca 的值,如下所示 .

我找到的最接近的答案是this one但是我无法让它按原样运行 . 我认为 replace 模块比lineinfile更适合,因为我宁愿不重写整行,并且想要替换文件中出现的任意数量 .

经过一些更改,这是我最接近的,但我还没弄清楚为什么我的语法关闭:

---
- hosts: myhost5
  become: yes
  tasks:
  - name: grab conf file names
    shell: ls /etc/httpd/conf.d/V*.conf
    register: vhost_files
  - name: replace text
    replace:
      dest: '{{ item.0 }}'
      regexp: '{{ item.1.regexp }}'
      line: '{{ item.1.line}}'
      backrefs: yes
      backup: yes
    with_nested:
      - "{{vhost_files}}"
      - "{{text_to_replace}}"
  vars:
    text_to_replace:
      - { "regexp: 'mywildcard2014.crt', line: 'mywildcard.2016.crt'" }
      - { "regexp: 'mywildcard2048_2014.key', line: 'mywildcard.2016.key'" }
      - { "regexp: 'gd_bundle2014.crt', line: 'mywildcard.2016.ca-bundle'" }

  handlers:
  - name: restart apache
    service: name=httpd state=restarted

我得到的回应是:

the field 'args' has an invalid value, which appears to include a 
variable that is undefined. The error was: 'dict object' has no attribute 'regexp'

1 回答

  • 3

    首先,您需要删除不必要的双引号:

    - { regexp: 'mywildcard2014.crt', line: 'mywildcard.2016.crt' }
    

    但是代码中还有许多其他小错误 .
    还要记住,使用shell命令而不是模块不是一种Ansible方式 .
    考虑使用 find 模块而不是 shell: ls .

    ---
    - hosts: myhost5
      become: yes
      vars:
        text_to_replace:
          - { regexp: 'mywildcard2014.crt', line: 'mywildcard.2016.crt' }
          - { regexp: 'mywildcard2048_2014.key', line: 'mywildcard.2016.key' }
          - { regexp: 'gd_bundle2014.crt', line: 'mywildcard.2016.ca-bundle' }
      tasks:
      - name: grab conf file names
        find:
          pattern: V*.conf
          path: /etc/httpd/conf.d/
        register: vhost_files
      - name: replace text
        replace:
          dest: '{{ item.0.path }}'
          regexp: '{{ item.1.regexp }}'
          replace: '{{ item.1.line}}'
          backup: yes
        with_nested:
          - "{{vhost_files.files}}"
          - "{{text_to_replace}}"
        notify: restart apache
    
      handlers:
      - name: restart apache
        service: name=httpd state=restarted
    

相关问题