In Ansible, how do I add a line to the end of a file?

可紊 提交于 2020-01-10 08:15:46

问题


I would expect this to be pretty simple. I'm using the lineinfile module like so:

- 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

The problem I'm having is that it's replacing the last line in the file (which is fi) with my new line rather than appending the line. This produces a syntax error.

Do I have the parameters correct? I've tried setting regexp to both '^' and '' (blank). Is there another way to go about this?

I'm using Ansible 1.3.3.


回答1:


Apparently ansible has matured and now (version >2.4.0) according to the documentation, The defaults when only the line is specified will append a given line to the destination file:

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



回答2:


The Ansible discussion group helped get me sorted out on this. The problem is the regexp parameter.

Since I only want the line appended to the file once, I need the regexp to match the line as closely as possible. This is complicated in my case by the fact that my line includes variables. But, assuming the line started [[ -s $HOME/.pythonbrew, I found the following to be sufficient:

- 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


来源:https://stackoverflow.com/questions/19688885/in-ansible-how-do-i-add-a-line-to-the-end-of-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!