{"record":{"id":"dc5b980d2cc614db","repo":"ansible/ansible","slug":"an-error-occurred-while-trying-to-read-the-file-f","errorCode":null,"errorMessage":"An error occurred while trying to read the file {file_name!r}.","messagePattern":"An error occurred while trying to read the file (.+?)\\.","errorType":"exception","errorClass":"AnsibleParserError","httpStatus":null,"severity":"error","filePath":"lib/ansible/parsing/dataloader.py","lineNumber":218,"sourceCode":"\n        :arg file_name: The name of the file to read.  If this is a relative\n            path, it will be expanded relative to the basedir\n        :raises AnsibleFileNotFound: if the file_name does not refer to a file\n        :raises AnsibleParserError: if we were unable to read the file\n        :return: Returns a byte string of the file contents\n        \"\"\"\n        if not file_name or not isinstance(file_name, str):\n            raise TypeError(f\"Invalid filename {file_name!r}.\")\n\n        file_name = self.path_dwim(file_name)\n\n        try:\n            data = pathlib.Path(file_name).read_bytes()\n        except FileNotFoundError as ex:\n            # DTFIX-FUTURE: why not just let the builtin one fly?\n            raise AnsibleFileNotFound(\"Unable to retrieve file contents.\", file_name=file_name) from ex\n        except OSError as ex:\n            raise AnsibleParserError(f\"An error occurred while trying to read the file {file_name!r}.\") from ex\n\n        data = Origin(path=file_name).tag(data)\n\n        return self._decrypt_if_vault_data(data)\n\n    def get_basedir(self) -> str:\n        \"\"\" returns the current basedir \"\"\"\n        return self._basedir\n\n    def set_basedir(self, basedir: str) -> None:\n        \"\"\" sets the base directory, used to find files when a relative path is given \"\"\"\n        self._basedir = os.path.abspath(basedir)\n\n    def path_dwim(self, given: str) -> str:\n        \"\"\"\n        make relative paths work like folks expect.\n        \"\"\"\n","sourceCodeStart":200,"sourceCodeEnd":236,"githubUrl":"https://github.com/ansible/ansible/blob/9cf16a4aca7898481c257f1e17ad28d0b67b1f85/lib/ansible/parsing/dataloader.py#L200-L236","documentation":"In DataLoader._get_file_contents, any OSError from read_bytes() that is not FileNotFoundError (permission denied, is-a-directory, I/O error, name too long) is wrapped in AnsibleParserError 'An error occurred while trying to read the file {file_name!r}' with the original exception chained. The file exists but could not be read as bytes.","triggerScenarios":"Path exists but is a directory (IsADirectoryError); mode bits deny read to the controller user (PermissionError); file on an unavailable mount (OSError); path exceeds NAME_MAX.","commonSituations":"Ansible controller running as a user without read access to vault/vars files owned by root; playbook pointing a loader call at a directory; NFS/sshfs mounts dropped mid-run.","solutions":["Inspect the resolved path with ls -la and confirm it is a regular file","Fix permissions/ownership so the controller user can read it (chmod a+r or chown)","Correct the path if it accidentally names a directory","Remount/repair the filesystem if the underlying OSError is I/O related (see the chained 'from' exception)"],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":"p = Path(loader.path_dwim(filename))\nif not p.is_file():\n    raise AnsibleError(f'{p} is not a regular file')\nif not os.access(p, os.R_OK):\n    raise AnsibleError(f'{p} is not readable by uid {os.getuid()}')","typeGuard":null,"tryCatchPattern":"from ansible.errors import AnsibleParserError\n\ntry:\n    data = loader.get_file_contents(filename)\nexcept AnsibleParserError as e:\n    cause = e.__cause__  # the original OSError: PermissionError, IsADirectoryError, ...\n    if isinstance(cause, PermissionError):\n        ...  # actionable message about modes/ownership\n    raise","preventionTips":["Run the controller with a user that has read access to all vault/vars files","Point loader calls at files, never directories","Handle unstable mounts (NFS/sshfs) before long playbook runs"],"tags":["dataloader","io","permissions","parser-error"],"backgroundTag":null,"analyzedSha":"9cf16a4aca7898481c257f1e17ad28d0b67b1f85","analyzedAt":"2026-08-15T00:15:47.100Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}