Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ansible

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.

like image 393
klenwell Avatar asked Oct 30 '13 16:10

klenwell


People also ask

How do you modify a line in a file using Ansible?

To modify a line, you need to use the Ansible backrefs parameter along with the regexp parameter. This should be used with state=present. If the regexp does not match any line, then the file is not changed. If the regexp matches a line or multiple lines, then the last matched line will be replaced.

What is marker in Ansible?

Ansible blockinfile module is used to insert/update/remove a block of lines. The block will be surrounded by a marker, like begin and end, to make the task idempotent. If you want to modify/ insert only a line, use lineinfile module.


2 Answers

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 
like image 67
klenwell Avatar answered Sep 19 '22 13:09

klenwell


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 
like image 28
shlomoa Avatar answered Sep 21 '22 13:09

shlomoa