如何通过使用ansible忽略具有特定字符的行来替换特定行?

How to replace a specfic line by also ignoring lines with a specific character using ansible?

假设这是我的 SSL 的 nginx 配置文件

#ssl_certificate "/etc/pki/nginx/server.crt" 
    #ssl_certificate_key "/etc/pki/nginx/private/server.key";


    ssl_certificate /etc/pki/nginx/server.crt  
ssl_certificate_key /etc/pki/nginx/private/server.key      


#    ssl_certificate "/etc/pki/nginx/server.crt";
  #     ssl_certificate_key "/etc/pki/nginx/private/server.key" 

我希望能够用 ansible(lineinfile 模块)替换未注释的 ssl_certificate 行

这是我的 "ssl_certificate" 行代码

lineinfile:
       path: /etc/nginx/sites-enabled/site1
       regexp: '^ssl_certificate | ssl_certificate '
       line: 'ssl_certificate /etc/letsencrypt/ssl/site1/fullchain.crt'

出于某种原因,这仅在我要替换的行设置在该行的开头时才有效,并且如果 "ssl_certificate" 与“#”分开,它会从底部替换注释行。

有没有办法让 lineinfile 忽略其中包含“#”的行?

我尝试将 [^#] 与其他东西以及 insertbefore 和 inserafter 等结合使用,但没有任何效果,它要么替换注释行,要么在底部添加新行。

如果您只想替换文件中的单个引用,则以下任务有效,

- name: Replace the cert file
  lineinfile:
       path: /root/tmp.txt
       regexp: '^\s*ssl_certificate\s.*'
       line: 'ssl_certificate /etc/letsencrypt/ssl/site1/fullchain.crt'

如果你想替换多行,你可以使用下面的任务,

- name: Replace cert file
  replace:
        path: /root/tmp.txt
        regexp: '^\s*ssl_certificate\s.*'
        replace: 'ssl_certificate /etc/letsencrypt/ssl/site1/fullchain.crt'

相应地更新文件路径。