I have come across a peculiar issue while using ansible. The problem is very strange and dangerous. I have a written a code to insert data in a particular section of a file i.e to add line after [database] in say /etc/cinder/cinder.conf.

The problem is I have noticed sometimes it adds the content properly after the tag [database] , but sometimes it gets confused by seeing a line like # put ur infore here for [database] in the file and adds our required line below it instead of where it should actually put it.

   - name: Adding Entries in "/etc/cinder/cinder.conf"
      dest: "/etc/cinder/cinder.conf"
      insertafter:  "{{ item.inserts }}"
      state: present
      line: "{{ item.lines }}"
      - { inserts: '\[database\]', lines: 'rpc_backend = rabbit' }

This situation is quite dangerous in a production environment! How can I add the data correctly?

2 Answers 2


To avoid matching in a comment, anchor your regexp to the beginning of the line:

- { inserts: '^\[database\]', lines: 'rpc_backend = rabbit' }
  • Oh God !! So silly of me to forget about this,, thanks a ton ,, I believe this would resolve my concern,, Jun 25, 2017 at 13:26
  • 2
    @Mohd If this solves your issue, please consider accepting the answer. If you're happy with the answer, accepting it and maybe even upvoting it is the best way to say "Thank You!" :-)
    – Kusalananda
    Jun 25, 2017 at 17:29

You can use ini_file module from general collection:

- name: Adding Entries in "/etc/cinder/cinder.conf"
    path: "/etc/cinder/cinder.conf"
    section: database
    option: rpc_backend
    value: rabbit
    backup: true

To install the collection, run

$ ansible-galaxy collection install community.general

or add it to the requirements.yaml as

  - name: community.general
    version: 5.0.1

and run

$ ansible-galaxy install -r requirements.yaml

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .