diff --git a/changelogs/fragments/8057-pam_limits-check-mode.yml b/changelogs/fragments/8057-pam_limits-check-mode.yml new file mode 100644 index 0000000000..f6f034e9b8 --- /dev/null +++ b/changelogs/fragments/8057-pam_limits-check-mode.yml @@ -0,0 +1,2 @@ +bugfixes: + - "pam_limits - when the file does not exist, do not create it in check mode (https://github.com/ansible-collections/community.general/issues/8050, https://github.com/ansible-collections/community.general/pull/8057)." diff --git a/plugins/modules/pam_limits.py b/plugins/modules/pam_limits.py index 7b363ec2bb..f97ea6602b 100644 --- a/plugins/modules/pam_limits.py +++ b/plugins/modules/pam_limits.py @@ -175,7 +175,6 @@ def main(): limits_conf = '/etc/security/limits.conf' module = AnsibleModule( - # not checking because of daisy chain to file module argument_spec=dict( domain=dict(required=True, type='str'), limit_type=dict(required=True, type='str', choices=pam_types), @@ -201,6 +200,7 @@ def main(): new_comment = module.params['comment'] changed = False + does_not_exist = False if os.path.isfile(limits_conf): if not os.access(limits_conf, os.W_OK): @@ -208,7 +208,7 @@ def main(): else: limits_conf_dir = os.path.dirname(limits_conf) if os.path.isdir(limits_conf_dir) and os.access(limits_conf_dir, os.W_OK): - open(limits_conf, 'a').close() + does_not_exist = True changed = True else: module.fail_json(msg="directory %s is not writable (check presence, access rights, use sudo)" % limits_conf_dir) @@ -224,15 +224,20 @@ def main(): space_pattern = re.compile(r'\s+') + if does_not_exist: + lines = [] + else: + with open(limits_conf, 'rb') as f: + lines = list(f) + message = '' - f = open(limits_conf, 'rb') # Tempfile nf = tempfile.NamedTemporaryFile(mode='w+') found = False new_value = value - for line in f: + for line in lines: line = to_native(line, errors='surrogate_or_strict') if line.startswith('#'): nf.write(line) @@ -323,17 +328,17 @@ def main(): message = new_limit nf.write(new_limit) - f.close() nf.flush() - with open(limits_conf, 'r') as content: - content_current = content.read() - with open(nf.name, 'r') as content: content_new = content.read() if not module.check_mode: - # Copy tempfile to newfile + if does_not_exist: + with open(limits_conf, 'a'): + pass + + # Move tempfile to newfile module.atomic_move(nf.name, limits_conf) try: @@ -344,7 +349,7 @@ def main(): res_args = dict( changed=changed, msg=message, - diff=dict(before=content_current, after=content_new), + diff=dict(before=b''.join(lines), after=content_new), ) if backup: