The short answer is no. If you want to modify the string with backrefs, then lineinfile will not create the line if it doesn’t exist.
But step back and consider your options for managing your override.conf file.
A. The best scenario is to take total ownership of the entire file, generating it from variables in your project. You have to take changes into account as you upgrade kafka etc, but you should do that in any case.
B. If for some reasons you aren’t ready or able to take ownership of the whole file, then the next best thing is to at least take complete ownership of the ‘Environment="KAFKA…’ line, and build it from information in your project. You can still have appropriate differences on various instances, but that would all by controlled by data and logic in your Ansible project. See the example below.
C. The absolute worst scenario, the situation where you should be saying, “How can we move to option ‘B’ or ‘A’ as soon as possible?”, is when you try to tweak a line that may or may not exist, in a file that may or may not exist, and that may have unknown variances between hosts for reasons that (apparently) aren’t coming from your configuration management system. As a stop-gap step in a house-on-fire situation, you’ve got to do what you’ve got to do. But you should stop doing it as soon as possible.
That’s not to say that ‘C’ doesn’t work; it does, and I’ve managed files that way for years. But I got in that situation for two reasons: 1) Nobody told me what I just told you, and 2) I figured my problem was to tweak a line in a file, and if there was an Ansible module to do just that, then it must be an okay way to do it.
Here’s a short playbook with variables to inform the line in question. Clearly you could use group_vars, host_vars, and/or inventory variables to tailor the result for individual hosts. But I strongly encourage you to pull the responsibility for that entire line (option ‘B’) or better yet that entire file (option ‘A’) into your Ansible project.
---
# sameer-0.yml
- name: KAFKA_JMX options management
hosts: localhost
gather_facts: false
vars:
filename: sameer-0-override.conf
kafka_jmx_opts:
- '-javaagent:/usr/share/java/kafka/jolokia.jar=port=8778,host=pilot01.test'
- '-Dcom.sun.management.jmxremote'
- '-Dcom.sun.management.jmxremote.authenticate=false'
- '-Dcom.sun.management.jmxremote.ssl=false'
- '-Djava.rmi.server.hostname=pilot01.test'
- '-Dcom.sun.management.jmxremote.rmi.port=1099'
kafka_jmx_opts_str: 'KAFKA_JMX_OPTS={{ kafka_jmx_opts | join(" ") }}'
tasks:
- name: Manage kafka_jms_opts in override.conf
ansible.builtin.lineinfile:
path: '{{ filename }}'
regexp: 'Environment="KAFKA_JMX_OPTS=.*"'
line: 'Environment="{{ kafka_jmx_opts_str }}"'
state: present
create: true # You should have "owner:", "group:", and "mode:" here too.