ansible-rs 1.1.0

A Rust wrapper library for Ansible command-line tools (Linux/Unix only)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
//! Core Ansible command execution and module management.
//!
//! This module provides the main [`Ansible`] struct for executing ad-hoc Ansible commands
//! and the [`Module`] system for type-safe module configuration.

use crate::command_config::CommandConfig;
use crate::errors::{AnsibleError, Result};
use std::ffi::OsStr;
use std::fmt::{Display, Formatter};
use std::process;

/// Package states for package management modules.
///
/// Used with package-related modules like `package`, `apt`, `yum`, etc.
///
/// # Examples
///
/// ```rust
/// use ansible::PackageState;
///
/// let state = PackageState::Present;
/// assert_eq!(state.to_string(), "present");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum PackageState {
    /// Package should be installed
    Present,
    /// Package should be removed
    Absent,
    /// Package should be updated to the latest version
    Latest,
}

impl Display for PackageState {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            PackageState::Present => write!(f, "present"),
            PackageState::Absent => write!(f, "absent"),
            PackageState::Latest => write!(f, "latest"),
        }
    }
}

/// Service states for service management modules.
///
/// Used with service-related modules like `service`, `systemd`, etc.
///
/// # Examples
///
/// ```rust
/// use ansible::ServiceState;
///
/// let state = ServiceState::Started;
/// assert_eq!(state.to_string(), "started");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum ServiceState {
    /// Service should be running
    Started,
    /// Service should be stopped
    Stopped,
    /// Service should be restarted
    Restarted,
    /// Service configuration should be reloaded
    Reloaded,
}

impl Display for ServiceState {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ServiceState::Started => write!(f, "started"),
            ServiceState::Stopped => write!(f, "stopped"),
            ServiceState::Restarted => write!(f, "restarted"),
            ServiceState::Reloaded => write!(f, "reloaded"),
        }
    }
}

/// File states for file management modules.
///
/// Used with file-related modules like `file`, `copy`, `template`, etc.
///
/// # Examples
///
/// ```rust
/// use ansible::FileState;
///
/// let state = FileState::Directory;
/// assert_eq!(state.to_string(), "directory");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum FileState {
    /// Path should be a regular file
    File,
    /// Path should be a directory
    Directory,
    /// Path should be a symbolic link
    Link,
    /// Path should not exist
    Absent,
    /// Path should exist (create if missing)
    Touch,
}

impl Display for FileState {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            FileState::File => write!(f, "file"),
            FileState::Directory => write!(f, "directory"),
            FileState::Link => write!(f, "link"),
            FileState::Absent => write!(f, "absent"),
            FileState::Touch => write!(f, "touch"),
        }
    }
}

/// User states for user management modules.
///
/// Used with user-related modules like `user`, `group`, etc.
///
/// # Examples
///
/// ```rust
/// use ansible::UserState;
///
/// let state = UserState::Present;
/// assert_eq!(state.to_string(), "present");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum UserState {
    /// User should exist
    Present,
    /// User should be removed
    Absent,
}

impl Display for UserState {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            UserState::Present => write!(f, "present"),
            UserState::Absent => write!(f, "absent"),
        }
    }
}

/// Group states for group management modules.
///
/// Used with group-related modules like `group`.
///
/// # Examples
///
/// ```rust
/// use ansible::GroupState;
///
/// let state = GroupState::Present;
/// assert_eq!(state.to_string(), "present");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum GroupState {
    /// Group should exist
    Present,
    /// Group should be removed
    Absent,
}

impl Display for GroupState {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            GroupState::Present => write!(f, "present"),
            GroupState::Absent => write!(f, "absent"),
        }
    }
}

/// Main Ansible command builder and executor.
///
/// The `Ansible` struct provides a fluent interface for building and executing
/// Ansible ad-hoc commands. It supports all major Ansible modules and provides
/// type-safe configuration options.
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust,no_run
/// use ansible::Ansible;
///
/// let mut ansible = Ansible::default();
/// ansible
///     .add_host("web01")
///     .set_inventory("hosts.yml");
///
/// // Execute a ping
/// let result = ansible.ping()?;
/// println!("Ping result: {}", result);
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Module Execution
///
/// ```rust,no_run
/// use ansible::{Ansible, Module, PackageState};
///
/// let mut ansible = Ansible::default();
/// ansible.add_host("all");
///
/// // Install a package
/// let module = Module::package("nginx", PackageState::Present);
/// let result = ansible.run(module)?;
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Environment Configuration
///
/// ```rust
/// use ansible::Ansible;
///
/// let mut ansible = Ansible::default();
/// ansible
///     .set_system_envs()
///     .filter_envs(["HOME", "PATH", "USER"]);
/// ```
#[derive(Debug, Clone)]
pub struct Ansible {
    pub(crate) command: String,
    pub(crate) cfg: CommandConfig,
    pub(crate) inventory: Option<String>,
    pub(crate) hosts: Vec<String>,
}

impl Default for Ansible {
    fn default() -> Self {
        Self {
            command: "ansible".into(),
            cfg: CommandConfig::default(),
            inventory: None,
            hosts: Vec::new(),
        }
    }
}

impl Display for Ansible {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.command)?;

        if let Some(ref inventory) = self.inventory {
            if !inventory.is_empty() {
                write!(f, " -i {}", inventory)?;
            }
        }

        if !self.hosts.is_empty() {
            write!(f, " {}", self.hosts.join(","))?;
        }

        if !self.cfg.args.is_empty() {
            write!(f, " {}", self.cfg.args.join(" "))?;
        }

        Ok(())
    }
}

impl Ansible {
    /// Set environment variables from the current system environment.
    ///
    /// This method copies all environment variables from the current process
    /// to be passed to the Ansible command. This is useful for ensuring
    /// Ansible has access to necessary environment variables like PATH, HOME, etc.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.set_system_envs();
    /// ```
    pub fn set_system_envs(&mut self) -> &mut Self {
        self.cfg.set_system_envs();
        self
    }

    /// Filter environment variables to only include specified keys.
    ///
    /// This method is useful for limiting which environment variables
    /// are passed to Ansible commands, which can improve security and
    /// reduce potential side effects.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible
    ///     .set_system_envs()
    ///     .filter_envs(["HOME", "PATH", "USER"]);
    /// ```
    pub fn filter_envs<T, S>(&mut self, iter: T) -> &mut Self
    where
        T: IntoIterator<Item = S>,
        S: AsRef<OsStr> + Display,
    {
        self.cfg.filter_envs(iter);
        self
    }

    /// Add a single environment variable.
    ///
    /// This method adds or overwrites an environment variable that will
    /// be passed to the Ansible command.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible
    ///     .add_env("ANSIBLE_HOST_KEY_CHECKING", "False")
    ///     .add_env("ANSIBLE_STDOUT_CALLBACK", "json");
    /// ```
    pub fn add_env(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.cfg.add_env(key, value);
        self
    }

    /// Add a single command-line argument.
    ///
    /// This method adds a raw command-line argument to the Ansible command.
    /// Use this for options not covered by specific methods.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible
    ///     .arg("--verbose")
    ///     .arg("--check");
    /// ```
    pub fn arg<S: AsRef<OsStr> + Display>(&mut self, arg: S) -> &mut Self {
        self.cfg.args.push(arg.to_string());
        self
    }

    /// Add multiple command-line arguments.
    ///
    /// This method adds multiple raw command-line arguments to the Ansible command.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.args(["--verbose", "--check", "--diff"]);
    /// ```
    pub fn args<T, S>(&mut self, args: T) -> &mut Self
    where
        T: IntoIterator<Item = S>,
        S: AsRef<OsStr> + Display,
    {
        for arg in args {
            self.arg(arg);
        }
        self
    }

    /// Add a single host or host pattern to the target list.
    ///
    /// This method adds a host or host pattern to target with Ansible commands.
    /// You can specify individual hosts, groups, or patterns.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible
    ///     .add_host("web01")
    ///     .add_host("db*")
    ///     .add_host("all");
    /// ```
    pub fn add_host<S: AsRef<OsStr> + Display>(&mut self, host: S) -> &mut Self {
        self.hosts.push(host.to_string());
        self
    }

    /// Add multiple hosts or host patterns to the target list.
    ///
    /// This method adds multiple hosts or host patterns at once.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.add_hosts(["web01", "web02", "db*"]);
    /// ```
    pub fn add_hosts<T, S>(&mut self, hosts: T) -> &mut Self
    where
        T: IntoIterator<Item = S>,
        S: AsRef<OsStr> + Display,
    {
        self.hosts.extend(hosts.into_iter().map(|h| h.to_string()));
        self
    }

    /// Clear all hosts from the target list.
    ///
    /// This method removes all previously added hosts and patterns.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.add_host("web01").add_host("web02");
    /// ansible.clear_hosts(); // Now no hosts are targeted
    /// ```
    pub fn clear_hosts(&mut self) -> &mut Self {
        self.hosts.clear();
        self
    }

    /// Set the inventory file or directory.
    ///
    /// This method specifies the inventory file or directory to use
    /// for host and group information.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.set_inventory("hosts.yml");
    /// ansible.set_inventory("/etc/ansible/hosts");
    /// ansible.set_inventory("production");
    /// ```
    pub fn set_inventory(&mut self, s: &str) -> &mut Self {
        self.inventory = Some(s.to_string());
        self
    }
    /// Configure output to use JSON format.
    ///
    /// This method sets environment variables to configure Ansible to output
    /// results in JSON format, which is useful for programmatic processing.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.set_output_json();
    /// ```
    pub fn set_output_json(&mut self) -> &mut Self {
        self.cfg
            .add_env("ANSIBLE_STDOUT_CALLBACK", "json")
            .add_env("ANSIBLE_LOAD_CALLBACK_PLUGINS", "True");
        self
    }

    /// Execute an Ansible module with the current configuration.
    ///
    /// This is the core method that executes Ansible commands. It takes a
    /// [`Module`] and executes it with the current host targets, inventory,
    /// and other configuration options.
    ///
    /// # Arguments
    ///
    /// * `m` - The module to execute
    ///
    /// # Returns
    ///
    /// Returns the combined stdout and stderr output from the Ansible command.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No module is specified (`Module::None`)
    /// - The Ansible command fails to execute
    /// - The command returns a non-zero exit code
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use ansible::{Ansible, Module};
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.add_host("localhost");
    ///
    /// let result = ansible.run(Module::Ping)?;
    /// println!("Ping result: {}", result);
    /// # Ok::<(), ansible::AnsibleError>(())
    /// ```
    pub fn run(&self, m: Module) -> Result<String> {
        if m == Module::None {
            return Err(AnsibleError::invalid_module("no module choice"));
        }
        let full_cmd = self.to_string();
        let cmd_vec: Vec<&str> = full_cmd.split_whitespace().collect();
        let mut cmd = process::Command::new(&self.command);
        cmd.envs(&self.cfg.envs);
        cmd.args(&cmd_vec.as_slice()[1..]);
        cmd.args(&self.cfg.args);
        cmd.args(m.to_args());
        let output = cmd.output()?;
        if !output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout).to_string();
            let stderr = String::from_utf8_lossy(&output.stderr).to_string();
            return Err(AnsibleError::command_failed(
                "Ansible command execution failed",
                output.status.code(),
                Some(stdout),
                Some(stderr),
            ));
        }
        let result = [output.stdout, "\n".as_bytes().to_vec(), output.stderr].concat();
        let s = String::from_utf8_lossy(&*result);

        Ok(s.to_string())
    }
    /// Execute a shell command on target hosts.
    ///
    /// This method uses the shell module to execute commands with shell processing,
    /// allowing for pipes, redirects, and variable expansion.
    ///
    /// # Arguments
    ///
    /// * `command` - The shell command to execute
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.add_host("localhost");
    ///
    /// let result = ansible.shell("ps aux | grep nginx")?;
    /// println!("Process list: {}", result);
    /// # Ok::<(), ansible::AnsibleError>(())
    /// ```
    ///
    /// # Security Note
    ///
    /// Be careful with shell injection when using user input.
    /// Consider using [`command`](Self::command) for simple command execution.
    pub fn shell(&self, command: impl Into<String>) -> Result<String> {
        self.run(Module::shell(command))
    }

    /// Execute a command on target hosts without shell processing.
    ///
    /// This method uses the command module to execute commands safely
    /// without shell processing, making it safer for user input.
    ///
    /// # Arguments
    ///
    /// * `command` - The command to execute
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.add_host("localhost");
    ///
    /// let result = ansible.command("ls -la /opt")?;
    /// println!("Directory listing: {}", result);
    /// # Ok::<(), ansible::AnsibleError>(())
    /// ```
    pub fn command(&self, command: impl Into<String>) -> Result<String> {
        self.run(Module::command(command))
    }

    /// Execute a local script on target hosts.
    ///
    /// This method transfers a local script to target hosts and executes it.
    ///
    /// # Arguments
    ///
    /// * `script_path` - Path to the local script file
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.add_host("localhost");
    ///
    /// let result = ansible.script("./deploy.sh")?;
    /// println!("Script output: {}", result);
    /// # Ok::<(), ansible::AnsibleError>(())
    /// ```
    pub fn script(&self, script_path: impl Into<String>) -> Result<String> {
        self.run(Module::script(script_path))
    }

    /// Test connectivity to target hosts using the ping module.
    ///
    /// This method uses the ping module to test basic connectivity
    /// and authentication to target hosts.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.add_host("all");
    ///
    /// let result = ansible.ping()?;
    /// println!("Ping result: {}", result);
    /// # Ok::<(), ansible::AnsibleError>(())
    /// ```
    pub fn ping(&self) -> Result<String> {
        self.run(Module::Ping)
    }

    /// Gather system facts from target hosts using the setup module.
    ///
    /// This method collects detailed information about target hosts
    /// including hardware, network, and operating system details.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use ansible::Ansible;
    ///
    /// let mut ansible = Ansible::default();
    /// ansible.add_host("localhost").set_output_json();
    ///
    /// let facts = ansible.setup()?;
    /// println!("System facts: {}", facts);
    /// # Ok::<(), ansible::AnsibleError>(())
    /// ```
    pub fn setup(&self) -> Result<String> {
        self.run(Module::Setup)
    }

    /// Copy files to remote hosts
    pub fn copy(&self, src: impl Into<String>, dest: impl Into<String>) -> Result<String> {
        self.run(Module::copy(src, dest))
    }

    /// Manage packages
    pub fn package(&self, name: impl Into<String>, state: PackageState) -> Result<String> {
        self.run(Module::package(name, state))
    }

    /// Manage services
    pub fn service(&self, name: impl Into<String>, state: ServiceState) -> Result<String> {
        self.run(Module::service(name, state))
    }

    /// Manage files and directories
    pub fn file(&self, path: impl Into<String>, state: FileState) -> Result<String> {
        self.run(Module::file(path, state))
    }

    /// Template files
    pub fn template(&self, src: impl Into<String>, dest: impl Into<String>) -> Result<String> {
        self.run(Module::template(src, dest))
    }

    /// Manage users
    pub fn user(&self, name: impl Into<String>, state: UserState) -> Result<String> {
        self.run(Module::user(name, state))
    }

    /// Manage groups
    pub fn group(&self, name: impl Into<String>, state: GroupState) -> Result<String> {
        self.run(Module::group(name, state))
    }

    /// Execute raw commands (bypasses module system)
    pub fn raw(&self, command: impl Into<String>) -> Result<String> {
        self.run(Module::raw(command))
    }

    /// Fetch files from remote hosts
    pub fn fetch(&self, src: impl Into<String>, dest: impl Into<String>) -> Result<String> {
        self.run(Module::fetch(src, dest))
    }

    /// Synchronize files and directories
    pub fn synchronize(&self, src: impl Into<String>, dest: impl Into<String>) -> Result<String> {
        self.run(Module::synchronize(src, dest))
    }

    /// Manage Git repositories
    pub fn git(&self, repo: impl Into<String>, dest: impl Into<String>) -> Result<String> {
        self.run(Module::git(repo, dest))
    }

    /// Manage cron jobs
    pub fn cron(&self, name: impl Into<String>, job: impl Into<String>) -> Result<String> {
        self.run(Module::cron(name, job))
    }

    /// Mount filesystems
    pub fn mount(&self, path: impl Into<String>, src: impl Into<String>, fstype: impl Into<String>) -> Result<String> {
        self.run(Module::mount(path, src, fstype))
    }

    /// Manage systemd services
    pub fn systemd(&self, name: impl Into<String>, state: ServiceState) -> Result<String> {
        self.run(Module::systemd(name, state))
    }
}

/// Type-safe representation of Ansible modules with their arguments.
///
/// The `Module` enum provides a type-safe way to construct Ansible modules
/// with their parameters. Each variant corresponds to a specific Ansible module
/// and includes the necessary parameters for that module.
///
/// # Examples
///
/// ## Basic Modules
///
/// ```rust
/// use ansible::Module;
///
/// // Ping module
/// let ping = Module::Ping;
///
/// // Shell command
/// let shell = Module::shell("uptime");
///
/// // Command execution
/// let cmd = Module::command("ls -la");
/// ```
///
/// ## Package Management
///
/// ```rust
/// use ansible::{Module, PackageState};
///
/// // Install a package
/// let install = Module::package("nginx", PackageState::Present);
///
/// // Remove a package
/// let remove = Module::package("apache2", PackageState::Absent);
/// ```
///
/// ## File Operations
///
/// ```rust
/// use ansible::{Module, FileState};
///
/// // Create a directory
/// let mkdir = Module::file("/opt/myapp", FileState::Directory);
///
/// // Copy a file
/// let copy = Module::copy("/local/file", "/remote/file");
/// ```
///
/// ## Service Management
///
/// ```rust
/// use ansible::{Module, ServiceState};
///
/// // Start a service
/// let start = Module::service("nginx", ServiceState::Started);
///
/// // Stop a service
/// let stop = Module::systemd("apache2", ServiceState::Stopped);
/// ```
#[derive(Debug, Default, PartialEq, Clone)]
pub enum Module {
    /// No module specified (default state)
    #[default]
    None,

    /// Ping module - tests connectivity to remote hosts
    ///
    /// Equivalent to `ansible -m ping`
    Ping,

    /// Setup module - gathers facts about remote hosts
    ///
    /// Equivalent to `ansible -m setup`
    Setup,

    /// Shell module - executes shell commands with shell processing
    ///
    /// Supports shell features like pipes, redirects, and variables.
    /// Use [`Module::command`] for simple command execution.
    Shell(String),

    /// Command module - executes commands without shell processing
    ///
    /// Safer than shell module as it doesn't process shell metacharacters.
    Command(String),

    /// Script module - executes local scripts on remote hosts
    ///
    /// Transfers and executes a local script on the remote host.
    Script(String),

    /// Copy module - copies files from local to remote hosts
    ///
    /// Supports file copying with permission and ownership management.
    Copy { src: String, dest: String },

    /// Package module - manages software packages
    ///
    /// Cross-platform package management that works with various package managers.
    Package { name: String, state: PackageState },

    /// Service module - manages system services
    ///
    /// Controls service state (start, stop, restart, reload).
    Service { name: String, state: ServiceState },

    /// File module - manages files and directories
    ///
    /// Creates, modifies, or removes files and directories with specified attributes.
    File { path: String, state: FileState },

    /// Template module - processes Jinja2 templates
    ///
    /// Renders Jinja2 templates and copies them to remote hosts.
    Template { src: String, dest: String },

    /// User module - manages user accounts
    ///
    /// Creates, modifies, or removes user accounts.
    User { name: String, state: UserState },

    /// Group module - manages user groups
    ///
    /// Creates, modifies, or removes user groups.
    Group { name: String, state: GroupState },

    /// Raw module - executes raw commands bypassing the module system
    ///
    /// Useful for commands that don't work well with the command module.
    Raw(String),

    /// Fetch module - retrieves files from remote hosts
    ///
    /// Downloads files from remote hosts to the local machine.
    Fetch { src: String, dest: String },

    /// Synchronize module - synchronizes files and directories
    ///
    /// Uses rsync to efficiently synchronize files between hosts.
    Synchronize { src: String, dest: String },

    /// Git module - manages Git repositories
    ///
    /// Clones, updates, or manages Git repositories.
    Git { repo: String, dest: String },

    /// Cron module - manages cron jobs
    ///
    /// Creates, modifies, or removes cron jobs.
    Cron { name: String, job: String },

    /// Mount module - manages filesystem mounts
    ///
    /// Mounts, unmounts, or manages filesystem mount points.
    Mount { path: String, src: String, fstype: String },

    /// Systemd module - manages systemd services
    ///
    /// Controls systemd services with additional systemd-specific features.
    Systemd { name: String, state: ServiceState },

    /// Custom module - allows using any Ansible module
    ///
    /// Provides access to modules not explicitly supported by this library.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Module;
    ///
    /// // Use a custom module
    /// let custom = Module::other("my_module", "param1=value1 param2=value2");
    /// ```
    Other { name: String, args: String },
}

impl Display for Module {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Module::None => write!(f, ""),
            Module::Ping => write!(f, "-m ping"),
            Module::Setup => write!(f, "-m setup"),
            Module::Shell(s) => write!(f, "-m shell -a {}", s),
            Module::Command(s) => write!(f, "-m command -a {}", s),
            Module::Script(s) => write!(f, "-m script -a {}", s),
            Module::Copy { src, dest } => write!(f, "-m copy -a 'src={} dest={}'", src, dest),
            Module::Package { name, state } => write!(f, "-m package -a 'name={} state={}'", name, state),
            Module::Service { name, state } => write!(f, "-m service -a 'name={} state={}'", name, state),
            Module::File { path, state } => write!(f, "-m file -a 'path={} state={}'", path, state),
            Module::Template { src, dest } => write!(f, "-m template -a 'src={} dest={}'", src, dest),
            Module::User { name, state } => write!(f, "-m user -a 'name={} state={}'", name, state),
            Module::Group { name, state } => write!(f, "-m group -a 'name={} state={}'", name, state),
            Module::Raw(s) => write!(f, "-m raw -a {}", s),
            Module::Fetch { src, dest } => write!(f, "-m fetch -a 'src={} dest={}'", src, dest),
            Module::Synchronize { src, dest } => write!(f, "-m synchronize -a 'src={} dest={}'", src, dest),
            Module::Git { repo, dest } => write!(f, "-m git -a 'repo={} dest={}'", repo, dest),
            Module::Cron { name, job } => write!(f, "-m cron -a 'name={} job={}'", name, job),
            Module::Mount { path, src, fstype } => write!(f, "-m mount -a 'path={} src={} fstype={}'", path, src, fstype),
            Module::Systemd { name, state } => write!(f, "-m systemd -a 'name={} state={}'", name, state),
            Module::Other { name, args } => write!(f, "-m {} -a {}", name, args),
        }
    }
}

impl Module {
    /// Convert module to command line arguments
    pub fn to_args(&self) -> Vec<String> {
        match self {
            Module::None => vec![],
            Module::Ping => vec!["-m".to_string(), "ping".to_string()],
            Module::Setup => vec!["-m".to_string(), "setup".to_string()],
            Module::Command(s) => vec!["-m".to_string(), "command".to_string(), "-a".to_string(), s.clone()],
            Module::Shell(s) => vec!["-m".to_string(), "shell".to_string(), "-a".to_string(), s.clone()],
            Module::Script(s) => vec!["-m".to_string(), "script".to_string(), "-a".to_string(), s.clone()],
            Module::Copy { src, dest } => vec!["-m".to_string(), "copy".to_string(), "-a".to_string(), format!("src={} dest={}", src, dest)],
            Module::Package { name, state } => vec!["-m".to_string(), "package".to_string(), "-a".to_string(), format!("name={} state={}", name, state)],
            Module::Service { name, state } => vec!["-m".to_string(), "service".to_string(), "-a".to_string(), format!("name={} state={}", name, state)],
            Module::File { path, state } => vec!["-m".to_string(), "file".to_string(), "-a".to_string(), format!("path={} state={}", path, state)],
            Module::Template { src, dest } => vec!["-m".to_string(), "template".to_string(), "-a".to_string(), format!("src={} dest={}", src, dest)],
            Module::User { name, state } => vec!["-m".to_string(), "user".to_string(), "-a".to_string(), format!("name={} state={}", name, state)],
            Module::Group { name, state } => vec!["-m".to_string(), "group".to_string(), "-a".to_string(), format!("name={} state={}", name, state)],
            Module::Raw(s) => vec!["-m".to_string(), "raw".to_string(), "-a".to_string(), s.clone()],
            Module::Fetch { src, dest } => vec!["-m".to_string(), "fetch".to_string(), "-a".to_string(), format!("src={} dest={}", src, dest)],
            Module::Synchronize { src, dest } => vec!["-m".to_string(), "synchronize".to_string(), "-a".to_string(), format!("src={} dest={}", src, dest)],
            Module::Git { repo, dest } => vec!["-m".to_string(), "git".to_string(), "-a".to_string(), format!("repo={} dest={}", repo, dest)],
            Module::Cron { name, job } => vec!["-m".to_string(), "cron".to_string(), "-a".to_string(), format!("name={} job={}", name, job)],
            Module::Mount { path, src, fstype } => vec!["-m".to_string(), "mount".to_string(), "-a".to_string(), format!("path={} src={} fstype={}", path, src, fstype)],
            Module::Systemd { name, state } => vec!["-m".to_string(), "systemd".to_string(), "-a".to_string(), format!("name={} state={}", name, state)],
            Module::Other { name, args } => vec!["-m".to_string(), name.clone(), "-a".to_string(), args.clone()],
        }
    }

    /// Create a shell module for executing shell commands.
    ///
    /// The shell module executes commands through the shell, allowing for
    /// shell features like pipes, redirects, and variable expansion.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Module;
    ///
    /// let module = Module::shell("ps aux | grep nginx");
    /// let module = Module::shell("echo $HOME");
    /// ```
    ///
    /// # Security Note
    ///
    /// Be careful with shell injection when using user input.
    /// Consider using [`Module::command`] for simple command execution.
    pub fn shell(command: impl Into<String>) -> Self {
        Module::Shell(command.into())
    }

    /// Create a command module for executing commands safely.
    ///
    /// The command module executes commands without shell processing,
    /// making it safer for user input but limiting shell features.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Module;
    ///
    /// let module = Module::command("ls -la /opt");
    /// let module = Module::command("systemctl status nginx");
    /// ```
    pub fn command(command: impl Into<String>) -> Self {
        Module::Command(command.into())
    }

    /// Create a script module for executing local scripts on remote hosts.
    ///
    /// The script is transferred to the remote host and executed there.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Module;
    ///
    /// let module = Module::script("/path/to/local/script.sh");
    /// let module = Module::script("./deploy.py");
    /// ```
    pub fn script(script_path: impl Into<String>) -> Self {
        Module::Script(script_path.into())
    }

    /// Create a copy module for transferring files to remote hosts.
    ///
    /// Copies files from the local machine to remote hosts with
    /// support for permissions, ownership, and backup options.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Module;
    ///
    /// let module = Module::copy("/local/config.conf", "/etc/myapp/config.conf");
    /// let module = Module::copy("./app.jar", "/opt/myapp/app.jar");
    /// ```
    pub fn copy(src: impl Into<String>, dest: impl Into<String>) -> Self {
        Module::Copy {
            src: src.into(),
            dest: dest.into(),
        }
    }

    /// Create a package module for managing software packages.
    ///
    /// The package module provides cross-platform package management
    /// that works with various package managers (apt, yum, dnf, etc.).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::{Module, PackageState};
    ///
    /// // Install a package
    /// let install = Module::package("nginx", PackageState::Present);
    ///
    /// // Remove a package
    /// let remove = Module::package("apache2", PackageState::Absent);
    ///
    /// // Update to latest version
    /// let update = Module::package("curl", PackageState::Latest);
    /// ```
    pub fn package(name: impl Into<String>, state: PackageState) -> Self {
        Module::Package {
            name: name.into(),
            state,
        }
    }

    /// Create a service module for managing system services.
    ///
    /// The service module controls service state across different
    /// service management systems (systemd, SysV init, etc.).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::{Module, ServiceState};
    ///
    /// // Start a service
    /// let start = Module::service("nginx", ServiceState::Started);
    ///
    /// // Stop a service
    /// let stop = Module::service("apache2", ServiceState::Stopped);
    ///
    /// // Restart a service
    /// let restart = Module::service("mysql", ServiceState::Restarted);
    /// ```
    pub fn service(name: impl Into<String>, state: ServiceState) -> Self {
        Module::Service {
            name: name.into(),
            state,
        }
    }

    /// Create a file module for managing files and directories.
    ///
    /// The file module can create, modify, or remove files and directories
    /// with specified permissions, ownership, and other attributes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::{Module, FileState};
    ///
    /// // Create a directory
    /// let mkdir = Module::file("/opt/myapp", FileState::Directory);
    ///
    /// // Create an empty file
    /// let touch = Module::file("/tmp/marker", FileState::Touch);
    ///
    /// // Remove a file
    /// let remove = Module::file("/tmp/old_file", FileState::Absent);
    /// ```
    pub fn file(path: impl Into<String>, state: FileState) -> Self {
        Module::File {
            path: path.into(),
            state,
        }
    }

    /// Create a template module for processing Jinja2 templates.
    ///
    /// The template module renders Jinja2 templates with variables
    /// and copies the result to remote hosts.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Module;
    ///
    /// let template = Module::template("nginx.conf.j2", "/etc/nginx/nginx.conf");
    /// let template = Module::template("app.properties.j2", "/opt/app/config/app.properties");
    /// ```
    pub fn template(src: impl Into<String>, dest: impl Into<String>) -> Self {
        Module::Template {
            src: src.into(),
            dest: dest.into(),
        }
    }

    /// Create a user module
    pub fn user(name: impl Into<String>, state: UserState) -> Self {
        Module::User {
            name: name.into(),
            state,
        }
    }

    /// Create a group module
    pub fn group(name: impl Into<String>, state: GroupState) -> Self {
        Module::Group {
            name: name.into(),
            state,
        }
    }

    /// Create a raw module
    pub fn raw(command: impl Into<String>) -> Self {
        Module::Raw(command.into())
    }

    /// Create a fetch module
    pub fn fetch(src: impl Into<String>, dest: impl Into<String>) -> Self {
        Module::Fetch {
            src: src.into(),
            dest: dest.into(),
        }
    }

    /// Create a synchronize module
    pub fn synchronize(src: impl Into<String>, dest: impl Into<String>) -> Self {
        Module::Synchronize {
            src: src.into(),
            dest: dest.into(),
        }
    }

    /// Create a git module
    pub fn git(repo: impl Into<String>, dest: impl Into<String>) -> Self {
        Module::Git {
            repo: repo.into(),
            dest: dest.into(),
        }
    }

    /// Create a cron module
    pub fn cron(name: impl Into<String>, job: impl Into<String>) -> Self {
        Module::Cron {
            name: name.into(),
            job: job.into(),
        }
    }

    /// Create a mount module
    pub fn mount(path: impl Into<String>, src: impl Into<String>, fstype: impl Into<String>) -> Self {
        Module::Mount {
            path: path.into(),
            src: src.into(),
            fstype: fstype.into(),
        }
    }

    /// Create a systemd module
    pub fn systemd(name: impl Into<String>, state: ServiceState) -> Self {
        Module::Systemd {
            name: name.into(),
            state,
        }
    }

    /// Create a custom module
    pub fn other(name: impl Into<String>, args: impl Into<String>) -> Self {
        Module::Other {
            name: name.into(),
            args: args.into(),
        }
    }
}