Update multiple lines using lineinfile

Hi,
I am new to Ansible and I am finding it hard to update multiple lines in 2 different stanza in a file. Below is the example:

I am trying to update gpgcheckvalue from 1 to 0 —> gpgcheck=1 to 0 in 2 stanzas below (updates and extras)

[base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
gpgcheck=1

#released updates
[updates]
name=CentOS-$releasever - Updates
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
gpgcheck=1

#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
gpgcheck=1

#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus&infra=$infra
#gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
gpgcheck=1
enabled=0

Below is my code in my yml.

  • name: Splunk Repo Update test
    become: true

lineinfile:
dest: ‘/etc/yum.repos.d/CentOS-Base.repo’
state: present
insertafter: ‘[updates]’
regexp: ‘gpgcheck’
line: ‘gpgcheck=1’

  • name: Splunk Repo Update test for Extra stanza
    become: true

lineinfile:
dest: ‘/etc/yum.repos.d/CentOS-Base.repo’
state: present
insertafter: ‘[extras]’
regexp: ‘gpgcheck’
line: ‘gpgcheck=1’

I am sure this is not the right way to code and it could be combined into 1 lineinfile option using with_items. But, for now, I want to try this separately and see if I could. If with_items is the right way, please let me know and I can change it. But, here is the situation though. When I run this code, it is updating the stanza which is at the end (updating gpgcheck in [centosplus] stanza). I understand it is trying to find the last instance of “gpgcheck” and updating the value. But, I want only these 2 stanzas to be updated and nothing before that or after that. How can I achieve that?? Hope my question makes sense.

Any help is greatly appreciated.

Thanks.

Make lineinfile in this situation is not easy, since this file is a ini-file use the ini_file module instead
https://docs.ansible.com/ansible/ini_file_module.html