2016-09-16 79 views
0

該項目將更新許多服務器上的通配符證書路徑,每個服務器都具有不同名稱的Vhost - *。conf文件。使用Ansible替換匹配文件中的多個單詞

我想搜索匹配V*.conf的文件,然後通過他們grep和替代值crtkey & ca如下所示。

我發現的最接近的答案是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' 

回答

0

第一所有,你需要刪除不必要的雙引號在這裏:

- { 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 
+0

我真的很感謝幫助清理那個骯髒的代碼!感謝Konstantin的幫助! – legatoproteus