How to delete a specific string from a line using ansible

I have some package added in yum exclude list in /etc/yum.conf and I want to remove a specific package from a exclude list

example:

exclude=java* exclude=kernel* java* exclude=java* kernel* exclude=kernel* abc* java* def*

I tried to add # but that do not serve the purpose and add comments to all exclude statement.

- name: Comment Java exclusion
  replace:
    path: /etc/yum.conf
    regexp: '(.*java*)'
    replace: '#\1'

Added more case scenarios.


Replace it with an empty string.

- name: Comment Java exclusion
  replace:
    path: /etc/yum.conf
    regexp: '(java\*\s*)'
    replace: ''

Changes to the regex:

  • .* would have removed the exclude= as well, so I removed it
  • The * needs to be escaped, it's a regex modifier
  • added \s* to remove trailing whitespace as well

EDIT

Even better:

- name: Comment Java exclusion
  replace:
    path: ~/ansible/test.blah
    regexp: '^(exclude=.*)java\*\s*'
    replace: '\1'

This makes sure that only the line starting with exclude= is affected and works even when java* is not the first item in the list.