运行 ansible insertLine 命令:完全错误,我不知道为什么

Running ansible insertLine command: Does the complete wrong thing, and i have no clue why

所以我的 configuration.yml(ansible 任务)

中有这一行
- name: inserting password into database.php
  lineinfile: dest=/vagrant/htdocs/app/config/database.php insertbefore="^\s*'pgsql' => array" regexp="^\s*'password'" line="                     'password'  => '',"

我正在尝试替换这个:

   'sqlite' => array(
        'driver'   => 'sqlite',
        'database' => __DIR__.'/../database/production.sqlite',
        'prefix'   => '',
    ),
    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'echoit',
        'username'  => 'root',
        'password'  => 'vp45tudsdt',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'port'      => 8889
    ),
    'pgsql' => array(
        'driver'   => 'pgsql',
        'host'     => 'localhost',
        'database' => 'forge',
        'username' => 'forge',
        'password' => '',
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ),

当我尝试 grep 正则表达式时:

 grep "^\s*'pgsql' => array" ./htdocs/app/config/database.default.php


 'pgsql' => array(

当我 grep 另一个时:

 grep "^\s*'password'" ./htdocs/app/config/database.php


                'password'  => 'xxxxxxx',
                'password' => '',
             'password'  => '',

所以我的正则表达式完全符合我的预期, 但是这个前线并没有像我想的那样工作,关于这个功能的可靠文档让我相信它会在 'pgsql' => array 之前进行最后一场比赛,但它只是不断替换最后一条路径,在这个案例'password' => '',

insertafterinsertbefore用于确定换行的位置如果找不到regexp,则不限制搜索区域。
根据 documentation:

regexp – The regular expression to look for in every line of the file.

最佳做法:使用 template module:

dbconn.php.j2的内容:

<?php

// {{ ansible_managed }}

$DBHost = 'localhost';
$DBName = '{{ db.dbname }}';
$DBLogin = '{{ db_user.name }}';
$DBPassword = '{{ db_user.password }}';

?>

Params 'db', 'dbuser' 存储在 host_vars and group_vars, password - in ansible vault.

剧本中的任务:

- name: template config files
  template:
    src="sites_params/{{ sitename }}/templates/include/dbconn.php.j2"
    dest="/www/{{ sitename }}/www/include/dbconn.php"
    owner=apache
    group=apache
    mode=0644
    setype=httpd_sys_content_t

PS 如果您使用 git,请从 git 中排除您的配置文件,例如 dbconn,只需将 sample 配置(无密码) , 盐等) 文件到你的项目中。