packer_rs 0.2.0

A Rust wrapper for HashiCorp Packer CLI
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
use derive_builder::Builder;
use std::path::PathBuf;
use std::process::Command;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum PackerError {
    #[error("Failed to execute Packer command: {0}")]
    ExecutionError(String),
    #[error("Failed to find Packer executable")]
    NotFound,
    #[error("Invalid configuration: {0}")]
    ConfigError(String),
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
}

type Result<T> = std::result::Result<T, PackerError>;

#[derive(Debug, Clone)]
pub struct Packer {
    executable: PathBuf,
    working_dir: Option<PathBuf>,
}

#[derive(Debug, Builder)]
pub struct BuildOptions {
    #[builder(default)]
    pub parallel_builds: Option<i32>,
    #[builder(default)]
    pub debug: bool,
    #[builder(default)]
    pub force: bool,
    #[builder(default)]
    pub timestamp_ui: bool,
    #[builder(default)]
    pub color: bool,
    #[builder(default)]
    pub vars: Vec<(String, String)>,
    #[builder(default)]
    pub var_files: Vec<PathBuf>,
}

impl Default for BuildOptions {
    fn default() -> Self {
        BuildOptions {
            parallel_builds: None,
            debug: false,
            force: false,
            timestamp_ui: false,
            color: true,
            vars: Vec::new(),
            var_files: Vec::new(),
        }
    }
}

impl Packer {
    /// Create a new Packer instance
    pub fn new() -> Result<Self> {
        if !is_packer_installed() {
            install_packer();
        }

        let executable = if cfg!(target_os = "windows") {
            PathBuf::from("./packer.exe")
        } else {
            PathBuf::from("./packer")
        };

        if !executable.exists() {
            return Err(PackerError::NotFound);
        }

        Ok(Self {
            executable,
            working_dir: None,
        })
    }

    /// Set working directory for Packer commands
    pub fn with_working_dir<P: Into<PathBuf>>(mut self, dir: P) -> Self {
        self.working_dir = Some(dir.into());
        self
    }

    /// Build images using a template
    pub fn build<P: AsRef<std::path::Path>>(
        &self,
        template: P,
        options: &BuildOptions,
    ) -> Result<()> {
        let mut cmd = self.base_command();
        cmd.arg("build");

        if options.debug {
            cmd.arg("-debug");
        }
        if options.force {
            cmd.arg("-force");
        }
        if let Some(parallel) = options.parallel_builds {
            cmd.args(["-parallel-builds", &parallel.to_string()]);
        }
        if !options.color {
            cmd.arg("-color=false");
        }
        if options.timestamp_ui {
            cmd.arg("-timestamp-ui");
        }

        // Add variables
        for (key, value) in &options.vars {
            cmd.arg(format!("-var={}={}", key, value));
        }

        // Add var files
        for var_file in &options.var_files {
            cmd.arg(format!("-var-file={}", var_file.display()));
        }

        cmd.arg(template.as_ref());

        self.execute_command(cmd)
    }

    /// Initialize a new Packer configuration
    pub fn init<P: AsRef<std::path::Path>>(&self, template: P) -> Result<()> {
        let mut cmd = self.base_command();
        cmd.arg("init").arg(template.as_ref());
        self.execute_command(cmd)
    }

    /// Validate a Packer template
    pub fn validate<P: AsRef<std::path::Path>>(&self, template: P) -> Result<()> {
        let mut cmd = self.base_command();
        cmd.arg("validate").arg(template.as_ref());
        self.execute_command(cmd)
    }

    /// Inspect a template
    pub fn inspect<P: AsRef<std::path::Path>>(&self, template: P) -> Result<String> {
        let mut cmd = self.base_command();
        cmd.arg("inspect").arg(template.as_ref());
        let output = cmd.output()?;

        if !output.status.success() {
            return Err(PackerError::ExecutionError(
                String::from_utf8_lossy(&output.stderr).to_string(),
            ));
        }

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Fix template
    pub fn fix<P: AsRef<std::path::Path>>(&self, template: P) -> Result<String> {
        let mut cmd = self.base_command();
        cmd.arg("fix").arg(template.as_ref());
        let output = cmd.output()?;

        if !output.status.success() {
            return Err(PackerError::ExecutionError(
                String::from_utf8_lossy(&output.stderr).to_string(),
            ));
        }

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Get version information
    pub fn version(&self) -> Result<String> {
        let mut cmd = self.base_command();
        cmd.arg("version");
        let output = cmd.output()?;

        if !output.status.success() {
            return Err(PackerError::ExecutionError(
                String::from_utf8_lossy(&output.stderr).to_string(),
            ));
        }

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Create a base command with common configuration
    fn base_command(&self) -> Command {
        let mut cmd = Command::new(&self.executable);
        if let Some(dir) = &self.working_dir {
            cmd.current_dir(dir);
        }
        cmd
    }

    /// Execute a command and handle its result
    fn execute_command(&self, mut cmd: Command) -> Result<()> {
        let status = cmd.status()?;

        if !status.success() {
            return Err(PackerError::ExecutionError(format!(
                "Command failed with exit code: {}",
                status
            )));
        }

        Ok(())
    }
}

// Plugin management functionality
impl Packer {
    /// Install a Packer plugin
    pub fn plugin_install(&self, plugin_name: &str) -> Result<()> {
        let mut cmd = self.base_command();
        cmd.args(["plugin", "install", plugin_name]);
        self.execute_command(cmd)
    }

    /// Remove a Packer plugin
    pub fn plugin_remove(&self, plugin_name: &str) -> Result<()> {
        let mut cmd = self.base_command();
        cmd.args(["plugin", "remove", plugin_name]);
        self.execute_command(cmd)
    }

    /// List installed plugins
    pub fn plugin_list(&self) -> Result<String> {
        let mut cmd = self.base_command();
        cmd.args(["plugin", "list"]);
        let output = cmd.output()?;

        if !output.status.success() {
            return Err(PackerError::ExecutionError(
                String::from_utf8_lossy(&output.stderr).to_string(),
            ));
        }

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }
}

// Console functionality
impl Packer {
    /// Start Packer console
    pub fn console<P: AsRef<std::path::Path>>(&self, template: P) -> Result<()> {
        let mut cmd = self.base_command();
        cmd.arg("console").arg(template.as_ref());
        self.execute_command(cmd)
    }
}

// HCL2 upgrade functionality
impl Packer {
    /// Upgrade HCL2 configuration
    pub fn hcl2_upgrade<P: AsRef<std::path::Path>>(&self, template: P) -> Result<String> {
        let mut cmd = self.base_command();
        cmd.arg("hcl2_upgrade").arg(template.as_ref());
        let output = cmd.output()?;

        if !output.status.success() {
            return Err(PackerError::ExecutionError(
                String::from_utf8_lossy(&output.stderr).to_string(),
            ));
        }

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }
}

fn is_packer_installed() -> bool {
    let packer_executable = if cfg!(target_os = "windows") {
        "./packer.exe"
    } else {
        "./packer"
    };

    Command::new(packer_executable)
        .arg("--version")
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false)
}

fn install_packer() {
    let target_os = std::env::consts::OS;
    // build_target::target_os().expect("Failed to get currentOS");

    match target_os {
        "windows" => {
            Command::new("powershell")
                .arg("-Command")
                .arg("Invoke-WebRequest -Uri https://releases.hashicorp.com/packer/1.7.8/packer_1.7.8_windows_amd64.zip -OutFile packer.zip; Expand-Archive -Path packer.zip -DestinationPath .;")
                .status()
                .expect("Failed to install Packer on Windows");
        }
        "macos" => {
            Command::new("sh")
                .arg("-c")
                .arg("curl -o packer.zip https://releases.hashicorp.com/packer/1.7.8/packer_1.7.8_darwin_amd64.zip && unzip packer.zip")
                .status()
                .expect("Failed to install Packer on macOS");
        }
        "linux" => {
            Command::new("sh")
                .arg("-c")
                .arg("curl -o packer.zip https://releases.hashicorp.com/packer/1.7.8/packer_1.7.8_linux_amd64.zip && unzip packer.zip")
                .status()
                .expect("Failed to install Packer on Linux");
        }
        _ => panic!("Unsupported OS"),
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use tempfile::TempDir;

    // Helper function to create a test environment
    fn setup_test_env() -> TempDir {
        tempfile::tempdir().unwrap()
    }

    #[test]
    fn test_build_options_builder() {
        let options = BuildOptionsBuilder::default()
            .debug(true)
            .force(true)
            .parallel_builds(Some(2))
            .vars(vec![("key".to_string(), "value".to_string())])
            .build()
            .unwrap();

        assert!(options.debug);
        assert!(options.force);
        assert_eq!(options.parallel_builds, Some(2));
        assert_eq!(options.vars.len(), 1);
        assert_eq!(options.vars[0].0, "key");
        assert_eq!(options.vars[0].1, "value");
    }

    #[test]
    fn test_packer_new_not_found() {
        // Create a clean test directory
        let test_dir = setup_test_env();
        println!("{test_dir:#?}");

        // Save current dir and change to test dir
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(test_dir.path()).unwrap();

        // Now we know for sure there's no packer executable here
        let packer = Packer::new();
        assert!(packer.is_ok());

        // Change back to original directory
        std::env::set_current_dir(original_dir).unwrap();
    }

    #[test]
    fn test_packer_with_working_dir() {
        let test_dir = setup_test_env();
        let packer = Packer {
            executable: PathBuf::from("dummy"),
            working_dir: None,
        }
        .with_working_dir(test_dir.path());

        assert_eq!(packer.working_dir.unwrap(), test_dir.path());
    }

    #[test]
    fn test_build_options_default() {
        let options = BuildOptions::default();
        assert!(!options.debug);
        assert!(!options.force);
        assert!(options.color);
        assert!(options.vars.is_empty());
        assert!(options.var_files.is_empty());
        assert_eq!(options.parallel_builds, None);
    }

    #[test]
    fn test_build_command_construction() {
        let packer = Packer {
            executable: PathBuf::from("dummy"),
            working_dir: None,
        };

        let _options = BuildOptionsBuilder::default()
            .debug(true)
            .force(true)
            .parallel_builds(Some(2))
            .vars(vec![("region".to_string(), "us-west-2".to_string())])
            .var_files(vec![PathBuf::from("vars.json")])
            .build()
            .unwrap();

        let cmd = packer.base_command();
        // We can't test the full command execution, but we can verify the struct is set up correctly
        assert_eq!(cmd.get_program(), PathBuf::from("dummy"));
    }
}