diff --git a/salt/modules/file.py b/salt/modules/file.py index d0847c669b76..49ca570e02df 100644 --- a/salt/modules/file.py +++ b/salt/modules/file.py @@ -5336,11 +5336,11 @@ def manage_file(name, # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) - if salt.utils.platform.is_windows(): - contents = os.linesep.join( - _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: + if salt.utils.platform.is_windows(): + contents = os.linesep.join( + _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: diff --git a/tests/integration/states/test_file.py b/tests/integration/states/test_file.py index db006161ad50..205c46b62f52 100644 --- a/tests/integration/states/test_file.py +++ b/tests/integration/states/test_file.py @@ -2696,6 +2696,26 @@ def test_binary_contents(self): except OSError: pass + def test_binary_contents_twice(self): + ''' + This test ensures that after a binary file is created, salt can confirm + that the file is in the correct state. + ''' + # Create a binary file + name = os.path.join(TMP, '1px.gif') + + # First run state ensures file is created + ret = self.run_state('file.managed', name=name, contents=BINARY_FILE) + self.assertSaltTrueReturn(ret) + + # Second run of state ensures file is in correct state + ret = self.run_state('file.managed', name=name, contents=BINARY_FILE) + self.assertSaltTrueReturn(ret) + try: + os.remove(name) + except OSError: + pass + @skip_if_not_root @skipIf(not HAS_PWD, "pwd not available. Skipping test") @skipIf(not HAS_GRP, "grp not available. Skipping test")