rash_core 2.20.0

Declarative shell scripting using Rust native bindings
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
/// ANCHOR: module
/// # jenkins_job
///
/// Manage Jenkins jobs and builds.
///
/// ## Attributes
///
/// ```yaml
/// check_mode:
///   support: full
/// ```
/// ANCHOR_END: module
/// ANCHOR: examples
/// ## Examples
///
/// ```yaml
/// - name: Create Jenkins job
///   jenkins_job:
///     name: myapp-build
///     state: present
///     url: http://jenkins.local
///     user: admin
///     password: secret
///
/// - name: Create Jenkins job with config XML
///   jenkins_job:
///     name: myapp-build
///     state: present
///     url: http://jenkins.local
///     user: admin
///     password: secret
///     config: |
///       <project>
///         <description>My app build job</description>
///         <builders>
///           <hudson.tasks.Shell>
///             <command>echo "Building"</command>
///           </hudson.tasks.Shell>
///         </builders>
///       </project>
///
/// - name: Trigger Jenkins build
///   jenkins_job:
///     name: myapp-build
///     state: present
///     url: http://jenkins.local
///     user: admin
///     password: secret
///     enabled: true
///
/// - name: Delete Jenkins job
///   jenkins_job:
///     name: old-job
///     state: absent
///     url: http://jenkins.local
///     user: admin
///     password: secret
///
/// - name: Trigger build with token
///   jenkins_job:
///     name: myapp-build
///     state: present
///     url: http://jenkins.local
///     user: admin
///     password: secret
///     token: build-token
///     enabled: true
/// ```
/// ANCHOR_END: examples
use crate::context::GlobalParams;
use crate::error::{Error, ErrorKind, Result};
use crate::modules::{Module, ModuleResult, parse_params};

#[cfg(feature = "docs")]
use rash_derive::DocJsonSchema;

use std::time::Duration;

use minijinja::Value;
use reqwest::blocking::Client;
#[cfg(feature = "docs")]
use schemars::{JsonSchema, Schema};
use serde::Deserialize;
use serde_json::json;
use serde_norway::Value as YamlValue;
use serde_norway::value;
#[cfg(feature = "docs")]
use strum_macros::{Display, EnumString};

#[derive(Debug, PartialEq, Deserialize)]
#[cfg_attr(feature = "docs", derive(JsonSchema, DocJsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Params {
    /// Name of the Jenkins job.
    pub name: String,
    /// Jenkins server URL.
    pub url: String,
    /// Jenkins username for authentication.
    pub user: String,
    /// Jenkins password or API token.
    pub password: String,
    /// Whether the job should be present or absent.
    /// **[default: `"present"`]**
    pub state: Option<State>,
    /// Job configuration XML content.
    pub config: Option<String>,
    /// Build token for triggering builds.
    pub token: Option<String>,
    /// Whether to trigger a build (only for state=present).
    #[serde(default)]
    pub enabled: bool,
    /// Timeout in seconds for API requests.
    #[serde(default = "default_timeout")]
    pub timeout: u64,
    /// If false, SSL certificates will not be validated.
    #[serde(default = "default_validate_certs")]
    pub validate_certs: bool,
}

#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
#[cfg_attr(feature = "docs", derive(EnumString, Display, JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum State {
    #[default]
    Present,
    Absent,
}

fn default_timeout() -> u64 {
    30
}

fn default_validate_certs() -> bool {
    true
}

fn normalize_url(url: &str) -> String {
    let url = url.trim();
    if url.ends_with('/') {
        url.to_string()
    } else {
        format!("{url}/")
    }
}

fn create_client(params: &Params) -> Result<Client> {
    Client::builder()
        .timeout(Duration::from_secs(params.timeout))
        .danger_accept_invalid_certs(!params.validate_certs)
        .build()
        .map_err(|e| {
            Error::new(
                ErrorKind::InvalidData,
                format!("Failed to create HTTP client: {e}"),
            )
        })
}

fn check_job_exists(
    client: &Client,
    url: &str,
    name: &str,
    user: &str,
    password: &str,
) -> Result<bool> {
    let job_url = format!("{url}job/{name}/api/json");
    let response = client
        .get(&job_url)
        .basic_auth(user, Some(password))
        .send()
        .map_err(|e| {
            Error::new(
                ErrorKind::SubprocessFail,
                format!("Failed to check job existence: {e}"),
            )
        })?;

    Ok(response.status().as_u16() == 200)
}

fn create_job(
    client: &Client,
    url: &str,
    name: &str,
    config: &str,
    user: &str,
    password: &str,
) -> Result<()> {
    let create_url = format!("{url}createItem?name={name}");
    let response = client
        .post(&create_url)
        .basic_auth(user, Some(password))
        .header("Content-Type", "application/xml")
        .body(config.to_string())
        .send()
        .map_err(|e| {
            Error::new(
                ErrorKind::SubprocessFail,
                format!("Failed to create Jenkins job: {e}"),
            )
        })?;

    let status = response.status();
    if !status.is_success() {
        let body = response.text().map_err(|e| {
            Error::new(
                ErrorKind::InvalidData,
                format!("Failed to read response body: {e}"),
            )
        })?;
        return Err(Error::new(
            ErrorKind::SubprocessFail,
            format!(
                "Failed to create job '{name}': HTTP {} - {body}",
                status.as_u16()
            ),
        ));
    }

    Ok(())
}

fn delete_job(client: &Client, url: &str, name: &str, user: &str, password: &str) -> Result<()> {
    let delete_url = format!("{url}job/{name}/doDelete");
    let response = client
        .post(&delete_url)
        .basic_auth(user, Some(password))
        .send()
        .map_err(|e| {
            Error::new(
                ErrorKind::SubprocessFail,
                format!("Failed to delete Jenkins job: {e}"),
            )
        })?;

    let status = response.status();
    if !status.is_success() && status.as_u16() != 302 {
        let body = response.text().map_err(|e| {
            Error::new(
                ErrorKind::InvalidData,
                format!("Failed to read response body: {e}"),
            )
        })?;
        return Err(Error::new(
            ErrorKind::SubprocessFail,
            format!(
                "Failed to delete job '{name}': HTTP {} - {body}",
                status.as_u16()
            ),
        ));
    }

    Ok(())
}

fn trigger_build(
    client: &Client,
    url: &str,
    name: &str,
    token: Option<&str>,
    user: &str,
    password: &str,
) -> Result<()> {
    let build_url = if let Some(tok) = token {
        format!("{url}job/{name}/build?token={tok}")
    } else {
        format!("{url}job/{name}/build")
    };

    let response = client
        .post(&build_url)
        .basic_auth(user, Some(password))
        .send()
        .map_err(|e| {
            Error::new(
                ErrorKind::SubprocessFail,
                format!("Failed to trigger Jenkins build: {e}"),
            )
        })?;

    let status = response.status();
    if !status.is_success() && status.as_u16() != 201 && status.as_u16() != 302 {
        let body = response.text().map_err(|e| {
            Error::new(
                ErrorKind::InvalidData,
                format!("Failed to read response body: {e}"),
            )
        })?;
        return Err(Error::new(
            ErrorKind::SubprocessFail,
            format!(
                "Failed to trigger build for '{name}': HTTP {} - {body}",
                status.as_u16()
            ),
        ));
    }

    Ok(())
}

fn get_default_config() -> String {
    r#"<?xml version='1.1' encoding='UTF-8'?>
<project>
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties/>
  <scm class="hudson.scm.NullSCM"/>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders/>
  <publishers/>
  <buildWrappers/>
</project>"#
        .to_string()
}

pub fn jenkins_job(params: Params, check_mode: bool) -> Result<ModuleResult> {
    trace!("params: {params:?}");

    let state = params.state.clone().unwrap_or_default();
    let url = normalize_url(&params.url);

    let client = create_client(&params)?;

    match state {
        State::Present => {
            let job_exists =
                check_job_exists(&client, &url, &params.name, &params.user, &params.password)?;

            let config = params.config.clone().unwrap_or_else(get_default_config);

            if !job_exists {
                if check_mode {
                    return Ok(ModuleResult {
                        changed: true,
                        output: Some(format!("Would create Jenkins job '{}'", params.name)),
                        extra: None,
                    });
                }

                create_job(
                    &client,
                    &url,
                    &params.name,
                    &config,
                    &params.user,
                    &params.password,
                )?;

                let extra = json!({
                    "name": params.name,
                    "url": params.url,
                    "state": "present",
                    "created": true,
                });

                let output = format!("Created Jenkins job '{}'", params.name);

                if params.enabled {
                    trigger_build(
                        &client,
                        &url,
                        &params.name,
                        params.token.as_deref(),
                        &params.user,
                        &params.password,
                    )?;
                }

                return Ok(ModuleResult {
                    changed: true,
                    output: Some(output),
                    extra: Some(value::to_value(extra)?),
                });
            }

            if params.enabled {
                if check_mode {
                    return Ok(ModuleResult {
                        changed: true,
                        output: Some(format!(
                            "Would trigger build for Jenkins job '{}'",
                            params.name
                        )),
                        extra: None,
                    });
                }

                trigger_build(
                    &client,
                    &url,
                    &params.name,
                    params.token.as_deref(),
                    &params.user,
                    &params.password,
                )?;

                let extra = json!({
                    "name": params.name,
                    "url": params.url,
                    "state": "present",
                    "build_triggered": true,
                });

                return Ok(ModuleResult {
                    changed: true,
                    output: Some(format!("Triggered build for Jenkins job '{}'", params.name)),
                    extra: Some(value::to_value(extra)?),
                });
            }

            let extra = json!({
                "name": params.name,
                "url": params.url,
                "state": "present",
                "exists": true,
            });

            Ok(ModuleResult {
                changed: false,
                output: Some(format!("Jenkins job '{}' already exists", params.name)),
                extra: Some(value::to_value(extra)?),
            })
        }
        State::Absent => {
            let job_exists =
                check_job_exists(&client, &url, &params.name, &params.user, &params.password)?;

            if !job_exists {
                return Ok(ModuleResult {
                    changed: false,
                    output: Some(format!("Jenkins job '{}' does not exist", params.name)),
                    extra: None,
                });
            }

            if check_mode {
                return Ok(ModuleResult {
                    changed: true,
                    output: Some(format!("Would delete Jenkins job '{}'", params.name)),
                    extra: None,
                });
            }

            delete_job(&client, &url, &params.name, &params.user, &params.password)?;

            let extra = json!({
                "name": params.name,
                "url": params.url,
                "state": "absent",
                "deleted": true,
            });

            Ok(ModuleResult {
                changed: true,
                output: Some(format!("Deleted Jenkins job '{}'", params.name)),
                extra: Some(value::to_value(extra)?),
            })
        }
    }
}

#[derive(Debug)]
pub struct JenkinsJob;

impl Module for JenkinsJob {
    fn get_name(&self) -> &str {
        "jenkins_job"
    }

    fn exec(
        &self,
        _: &GlobalParams,
        params: YamlValue,
        _vars: &Value,
        check_mode: bool,
    ) -> Result<(ModuleResult, Option<Value>)> {
        Ok((jenkins_job(parse_params(params)?, check_mode)?, None))
    }

    #[cfg(feature = "docs")]
    fn get_json_schema(&self) -> Option<Schema> {
        Some(Params::get_json_schema())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_norway::from_str;

    #[test]
    fn test_parse_params_basic() {
        let yaml = r#"
name: myapp-build
url: http://jenkins.local
user: admin
password: secret
"#;
        let value: YamlValue = from_str(yaml).unwrap();
        let params: Params = parse_params(value).unwrap();

        assert_eq!(params.name, "myapp-build");
        assert_eq!(params.url, "http://jenkins.local");
        assert_eq!(params.user, "admin");
        assert_eq!(params.password, "secret");
        assert_eq!(params.state, None);
        assert!(!params.enabled);
        assert_eq!(params.timeout, 30);
        assert!(params.validate_certs);
    }

    #[test]
    fn test_parse_params_with_config() {
        let yaml = r#"
name: myapp-build
url: http://jenkins.local
user: admin
password: secret
state: present
config: |
  <project>
    <description>My job</description>
  </project>
"#;
        let value: YamlValue = from_str(yaml).unwrap();
        let params: Params = parse_params(value).unwrap();

        assert_eq!(params.state, Some(State::Present));
        assert!(params.config.is_some());
        assert!(params.config.unwrap().contains("<project>"));
    }

    #[test]
    fn test_parse_params_with_state_absent() {
        let yaml = r#"
name: old-job
url: http://jenkins.local
user: admin
password: secret
state: absent
"#;
        let value: YamlValue = from_str(yaml).unwrap();
        let params: Params = parse_params(value).unwrap();

        assert_eq!(params.state, Some(State::Absent));
    }

    #[test]
    fn test_parse_params_with_build_trigger() {
        let yaml = r#"
name: myapp-build
url: http://jenkins.local
user: admin
password: secret
enabled: true
token: build-token
"#;
        let value: YamlValue = from_str(yaml).unwrap();
        let params: Params = parse_params(value).unwrap();

        assert!(params.enabled);
        assert_eq!(params.token, Some("build-token".to_string()));
    }

    #[test]
    fn test_parse_params_with_timeout() {
        let yaml = r#"
name: myapp-build
url: http://jenkins.local
user: admin
password: secret
timeout: 60
validate_certs: false
"#;
        let value: YamlValue = from_str(yaml).unwrap();
        let params: Params = parse_params(value).unwrap();

        assert_eq!(params.timeout, 60);
        assert!(!params.validate_certs);
    }

    #[test]
    fn test_normalize_url() {
        assert_eq!(
            normalize_url("http://jenkins.local"),
            "http://jenkins.local/"
        );
        assert_eq!(
            normalize_url("http://jenkins.local/"),
            "http://jenkins.local/"
        );
        assert_eq!(
            normalize_url("http://jenkins.local "),
            "http://jenkins.local/"
        );
    }

    #[test]
    fn test_default_state() {
        let state: State = Default::default();
        assert_eq!(state, State::Present);
    }

    #[test]
    fn test_parse_params_unknown_field() {
        let yaml = r#"
name: myapp-build
url: http://jenkins.local
user: admin
password: secret
unknown_field: value
"#;
        let value: YamlValue = from_str(yaml).unwrap();
        let error = parse_params::<Params>(value).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidData);
    }

    #[test]
    fn test_get_default_config() {
        let config = get_default_config();
        assert!(config.contains("<project>"));
        assert!(config.contains("<?xml"));
    }
}