diff --git a/plugins/modules/logrotate.py b/plugins/modules/logrotate.py index f27571a29c..185676c7e5 100644 --- a/plugins/modules/logrotate.py +++ b/plugins/modules/logrotate.py @@ -38,6 +38,7 @@ options: - Directory where logrotate configurations are stored. - Default is V(/etc/logrotate.d) for system-wide configurations. - Use V(~/.logrotate.d) for user-specific configurations. + - This directory must exist before using the module. type: path paths: description: @@ -271,6 +272,12 @@ extends_documentation_fragment: """ EXAMPLES = r""" +- name: Ensure logrotate config directory exists + ansible.builtin.file: + path: /etc/logrotate.d + state: directory + mode: '0755' + - name: Configure log rotation for Nginx community.general.logrotate: name: nginx @@ -483,9 +490,6 @@ class LogrotateConfig: self.config_file = self._get_config_path(self.params["enabled"]) - if not os.path.exists(self.config_dir): - os.makedirs(self.config_dir, mode=0o755, exist_ok=True) - def _get_config_path(self, enabled: bool) -> str: """Get config file path based on enabled state.""" base_path = os.path.join(self.config_dir, self.config_name) @@ -781,7 +785,11 @@ class LogrotateConfig: if self.params.get("backup"): backup_dir = self.params.get("backup_dir") or os.path.join(self.config_dir, ".backup") - os.makedirs(backup_dir, exist_ok=True) + if not os.path.exists(backup_dir): + self.module.fail_json( + msg=f"Backup directory '{backup_dir}' does not exist. " + f"Please create it manually if you want to use backup feature." + ) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") backup_file = os.path.join(backup_dir, f"{self.config_name}.backup.{timestamp}") @@ -797,6 +805,12 @@ class LogrotateConfig: self._validate_parameters() state = self.params["state"] + if not os.path.exists(self.config_dir): + self.module.fail_json( + msg=f"Config directory '{self.config_dir}' does not exist. " + f"Please create it manually or ensure the correct path is specified." + ) + if state == "absent": for suffix in ["", self.disabled_suffix]: config_path = os.path.join(self.config_dir, self.config_name + suffix)