From d6dededab8cfc68663ca5802b244f7cfb9a3a113 Mon Sep 17 00:00:00 2001 From: Mads Jensen Date: Wed, 1 Sep 2021 17:29:35 +0200 Subject: [PATCH] Use context manager for file handling in some system modules. (#65227) --- changelogs/fragments/65227.yml | 2 ++ lib/ansible/modules/service.py | 43 ++++++++++++++++------------------ 2 files changed, 22 insertions(+), 23 deletions(-) create mode 100644 changelogs/fragments/65227.yml diff --git a/changelogs/fragments/65227.yml b/changelogs/fragments/65227.yml new file mode 100644 index 00000000000..caa7fdde891 --- /dev/null +++ b/changelogs/fragments/65227.yml @@ -0,0 +1,2 @@ +bugfixes: + - system_service - use a context manager for file handling. diff --git a/lib/ansible/modules/service.py b/lib/ansible/modules/service.py index ed68ab42883..158a03c7e13 100644 --- a/lib/ansible/modules/service.py +++ b/lib/ansible/modules/service.py @@ -385,30 +385,27 @@ class Service(object): self.changed = None entry = '%s="%s"\n' % (self.rcconf_key, self.rcconf_value) - RCFILE = open(self.rcconf_file, "r") - new_rc_conf = [] - - # Build a list containing the possibly modified file. - for rcline in RCFILE: - # Parse line removing whitespaces, quotes, etc. - rcarray = shlex.split(rcline, comments=True) - if len(rcarray) >= 1 and '=' in rcarray[0]: - (key, value) = rcarray[0].split("=", 1) - if key == self.rcconf_key: - if value.upper() == self.rcconf_value: - # Since the proper entry already exists we can stop iterating. - self.changed = False - break - else: - # We found the key but the value is wrong, replace with new entry. - rcline = entry - self.changed = True - - # Add line to the list. - new_rc_conf.append(rcline.strip() + '\n') + with open(self.rcconf_file, "r") as RCFILE: + new_rc_conf = [] + + # Build a list containing the possibly modified file. + for rcline in RCFILE: + # Parse line removing whitespaces, quotes, etc. + rcarray = shlex.split(rcline, comments=True) + if len(rcarray) >= 1 and '=' in rcarray[0]: + (key, value) = rcarray[0].split("=", 1) + if key == self.rcconf_key: + if value.upper() == self.rcconf_value: + # Since the proper entry already exists we can stop iterating. + self.changed = False + break + else: + # We found the key but the value is wrong, replace with new entry. + rcline = entry + self.changed = True - # We are done with reading the current rc.conf, close it. - RCFILE.close() + # Add line to the list. + new_rc_conf.append(rcline.strip() + '\n') # If we did not see any trace of our entry we need to add it. if self.changed is None: