【问题标题】:In Ansible, how do I add a line to the end of a file?在 Ansible 中,如何在文件末尾添加一行?
【发布时间】:2013-10-30 16:44:28
【问题描述】:

我希望这很简单。我正在使用lineinfile 模块,如下所示:

- name: Update bashrc for PythonBrew for foo user
  lineinfile:
    dest=/home/foo/.bashrc
    backup=yes
    line="[[ -s ${pythonbrew.bashrc_path} ]] && source ${pythonbrew.bashrc_path}"
    owner=foo
    regexp='^'
    state=present
    insertafter=EOF
    create=True

我遇到的问题是它将文件中的最后一行(fi)替换为我的新行,而不是附加该行。这会产生语法错误。

我的参数是否正确?我尝试将正则表达式设置为'^'''(空白)。有没有其他方法可以解决这个问题?

我正在使用 Ansible 1.3.3。

【问题讨论】:

    标签: ansible


    【解决方案1】:

    The Ansible discussion group 帮助我解决了这个问题。问题在于regexp 参数。

    由于我只希望将行附加到文件一次,因此我需要正则表达式以尽可能接近地匹配该行。在我的情况下,这很复杂,因为我的行包含变量。但是,假设线路以[[ -s $HOME/.pythonbrew 开头,我发现以下内容就足够了:

    - name: Update bashrc for PythonBrew for foo user
      lineinfile:
        dest: /home/foo/.bashrc
        line: "[[ -s ${pythonbrew.bashrc_path} ]] && source ${pythonbrew.bashrc_path}"
        regexp: "^\[\[ -s \\$HOME/\.pythonbrew"
        owner: foo
        state: present
        insertafter: EOF
        create: True
    

    【讨论】:

    • 这是最初接受的答案。将 @shlomoa 的答案切换为 Ansible 的新版本(这就是它目前投票较少的原因。)
    【解决方案2】:

    显然ansible已经成熟,现在(版本>2.4.0)根据documentation,仅指定行时的默认值会将给定的行附加到目标文件:

        - name: Update bashrc for PythonBrew for foo user
          lineinfile:
            dest: /home/foo/.bashrc
            line: "[[ -s ${pythonbrew.bashrc_path} ]] && source {pythonbrew.bashrc_path}"
            owner: foo
    

    【讨论】:

    • 我验证它只为一行添加一次,但对于像“abc\ndef\n”这样的多行,它会继续添加。
    猜你喜欢
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 2014-05-29
    相关资源
    最近更新 更多