How do I add a line to a file?

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.

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

On Ansible 1.3.3.

I’ve added the question to Stack Overflow:

http://stackoverflow.com/q/19688885/1093087

IIRC, when the regexp match nothing (e.g: regexp=‘THAT STRING WILL NOT BE FOUND’)

then the line will be appended after the lat one

That did it. Thanks!

That seems like a real anti-pattern for what I imagine would be a pretty common use case.

Actually, it finally struck me what the regexp should really be since I only want one copy of the line in the file:

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

I’d like to match the whole line in the regexp param, but with the variable expansion, not sure how it would be done. In this case, the truncated regexp should be sufficient. Hopefully.

FYI, I wouldn’t recommend asking Ansible questions on SO.

It divides the community and most folks are here – mainly I just don’t like SO’s policy on closing questions and not wanting to have discourse/conversation. I understand why they do it, but just don’t personally prefer it.

Tim and company do read SO, but you’ll get an answer here a lot faster.

Yes,

adding as the regexp one matching the line - or just part of it- to be inserted is much better.
I have such cases too but answered too fast …

the variables {{ variable }} will be expanded in the rexgep string
but depending on their contents they might need quoted. For example to avoid the ‘.’ being interpreted by the regexp engine