Skip to main content

isothrum_runner/project/
variables.rs

1//! A Terraform module's input variables, read from its own files: each `variable` block of its
2//! `*.tf` files (HCL) and each `variable` object of its `*.tf.json` files, as Terraform reads
3//! them. Nothing runs: a caller lists what a folder asks for before it gives the values
4//! ([`crate::RunOptions::with_env`] for a plain one, a secret for a sensitive one, which the run's
5//! record then never keeps).
6
7use std::path::Path;
8
9use hcl::eval::{Context, Evaluate};
10use serde::{Deserialize, Serialize};
11
12use super::{Format, Project};
13use crate::Result;
14use crate::error::Error;
15
16/// One input variable of a Terraform module, as its `variable` block declares it.
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
18#[non_exhaustive]
19pub struct InputVariable {
20    /// Its name (the block's label).
21    pub name: String,
22    /// Its type constraint as written (`string`, `list(string)`, `object({ name = string })`),
23    /// when it has one.
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    #[serde(rename = "type")]
26    pub type_constraint: Option<String>,
27    /// Its default value, as JSON; none when the module needs it given.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub default: Option<serde_json::Value>,
30    /// Whether Terraform keeps it out of its output (`sensitive = true`): give it as a secret.
31    #[serde(default)]
32    pub sensitive: bool,
33    /// Its description, when it has one.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub description: Option<String>,
36}
37
38impl InputVariable {
39    /// Whether the module needs it given: it has no default.
40    #[must_use]
41    pub fn required(&self) -> bool {
42        self.default.is_none()
43    }
44}
45
46impl Project {
47    /// The input variables of this Terraform module, by name, read from its files.
48    ///
49    /// # Errors
50    ///
51    /// `unsupported` for a project of another format; `project_invalid` for a file that isn't
52    /// HCL or JSON as Terraform reads it, or a `variable` that isn't one; `io` when a file can't
53    /// be read.
54    pub fn variables(&self) -> Result<Vec<InputVariable>> {
55        if self.format != Format::Terraform {
56            return Err(Error::Unsupported {
57                what: format!("input variables of a {} project (only a Terraform module declares them)", self.format),
58            });
59        }
60        let mut found = Vec::new();
61        for file in &self.files {
62            let text = std::fs::read_to_string(file).map_err(Error::io(file, "read"))?;
63            let refused = |reason: String| Error::Project {
64                dir: self.dir.clone(),
65                reason: format!("{}: {reason}", file.display()),
66            };
67            if file.extension().is_some_and(|e| e == "json") {
68                found.extend(from_json(&text).map_err(refused)?);
69            } else if file.extension().is_some_and(|e| e == "tf") {
70                found.extend(from_hcl(&text).map_err(refused)?);
71            }
72        }
73        found.sort_by(|a, b| a.name.cmp(&b.name));
74        Ok(found)
75    }
76}
77
78/// The `variable` blocks of a `*.tf` file.
79fn from_hcl(text: &str) -> std::result::Result<Vec<InputVariable>, String> {
80    let body = hcl::parse(text).map_err(|e| format!("not HCL Terraform reads: {e}"))?;
81    body.blocks()
82        .filter(|b| b.identifier() == "variable")
83        .map(|block| {
84            let [label] = block.labels() else {
85                return Err("a `variable` block names one variable".to_owned());
86            };
87            let name = label.as_str().to_owned();
88            let mut variable = InputVariable {
89                name: name.clone(),
90                type_constraint: None,
91                default: None,
92                sensitive: false,
93                description: None,
94            };
95            for attribute in block.body().attributes() {
96                let value = || constant(&name, attribute.key(), attribute.expr());
97                match attribute.key() {
98                    "type" => {
99                        let written = hcl::format::to_string(attribute.expr()).map_err(|e| format!("variable `{name}`: its type: {e}"))?;
100                        variable.type_constraint = Some(written);
101                    }
102                    "default" => variable.default = Some(value()?),
103                    "sensitive" => variable.sensitive = value()? == serde_json::Value::Bool(true),
104                    "description" => variable.description = value()?.as_str().map(str::to_owned),
105                    _ => {}
106                }
107            }
108            Ok(variable)
109        })
110        .collect()
111}
112
113/// The value of `variable`'s attribute `key`, a constant (Terraform allows no reference there).
114fn constant(variable: &str, key: &str, expr: &hcl::Expression) -> std::result::Result<serde_json::Value, String> {
115    let value = expr
116        .evaluate(&Context::new())
117        .map_err(|e| format!("variable `{variable}`: its `{key}` isn't a constant: {e}"))?;
118    serde_json::to_value(value).map_err(|e| format!("variable `{variable}`: its `{key}`: {e}"))
119}
120
121/// One `variable` of a `*.tf.json` file, as Terraform's JSON syntax writes it.
122#[derive(Deserialize)]
123struct JsonVariable {
124    #[serde(default, rename = "type")]
125    type_constraint: Option<String>,
126    #[serde(default)]
127    default: Option<serde_json::Value>,
128    #[serde(default)]
129    sensitive: bool,
130    #[serde(default)]
131    description: Option<String>,
132}
133
134/// The `variable` objects of a `*.tf.json` file.
135fn from_json(text: &str) -> std::result::Result<Vec<InputVariable>, String> {
136    #[derive(Deserialize)]
137    struct File {
138        #[serde(default)]
139        variable: std::collections::BTreeMap<String, JsonVariable>,
140    }
141    let file: File = serde_json::from_str(text).map_err(|e| format!("not JSON Terraform reads: {e}"))?;
142    Ok(file
143        .variable
144        .into_iter()
145        .map(|(name, v)| InputVariable {
146            name,
147            type_constraint: v.type_constraint,
148            default: v.default,
149            sensitive: v.sensitive,
150            description: v.description,
151        })
152        .collect())
153}
154
155/// The input variables of the Terraform module in `dir`.
156///
157/// # Errors
158///
159/// As [`Project::open`] and [`Project::variables`] refuse.
160pub fn variables_of(dir: &Path) -> Result<Vec<InputVariable>> {
161    Project::open(dir, Some(Format::Terraform))?.variables()
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    fn module(files: &[(&str, &str)]) -> (tempfile::TempDir, Project) {
169        let dir = isothrum_test_support::dir_with(files).unwrap();
170        let project = Project::open(dir.path(), Some(Format::Terraform)).unwrap();
171        (dir, project)
172    }
173
174    #[test]
175    fn each_variable_block_is_read_with_its_type_default_and_sensitivity() {
176        let (_dir, project) = module(&[(
177            "main.tf",
178            r#"
179variable "region" {
180  type    = string
181  default = "us-east-1"
182}
183variable "token" {
184  type      = string
185  sensitive = true
186  description = "The API token."
187}
188variable "sizes" {
189  type    = map(number)
190  default = { small = 1, large = 4 }
191}
192resource "null_resource" "x" {}
193"#,
194        )]);
195        let vars = project.variables().unwrap();
196        let names: Vec<&str> = vars.iter().map(|v| v.name.as_str()).collect();
197        assert_eq!(names, ["region", "sizes", "token"]);
198        assert_eq!(vars[0].type_constraint.as_deref(), Some("string"));
199        assert_eq!(vars[0].default, Some(serde_json::json!("us-east-1")));
200        assert!(!vars[0].sensitive && !vars[0].required());
201        assert_eq!(vars[1].type_constraint.as_deref(), Some("map(number)"));
202        assert_eq!(vars[1].default, Some(serde_json::json!({"small": 1, "large": 4})));
203        assert!(vars[2].sensitive && vars[2].required());
204        assert_eq!(vars[2].description.as_deref(), Some("The API token."));
205    }
206
207    #[test]
208    fn a_json_file_declares_variables_too() {
209        let (_dir, project) = module(&[(
210            "vars.tf.json",
211            r#"{"variable": {"zone": {"type": "string", "default": "a"}, "key": {"sensitive": true}}}"#,
212        )]);
213        let vars = project.variables().unwrap();
214        assert_eq!(
215            vars.iter().map(|v| (v.name.as_str(), v.sensitive, v.required())).collect::<Vec<_>>(),
216            [("key", true, true), ("zone", false, false)]
217        );
218    }
219
220    #[test]
221    fn a_module_without_variables_has_none_and_a_broken_file_is_project_invalid() {
222        let (_empty, none) = module(&[("main.tf", "output \"x\" { value = 1 }\n")]);
223        assert_eq!(none.variables().unwrap(), []);
224        let (_broken, broken) = module(&[("main.tf", "variable \"x\" {\n")]);
225        assert_eq!(broken.variables().unwrap_err().code(), crate::ErrorCode::ProjectInvalid);
226    }
227
228    #[test]
229    fn another_format_has_no_variables() {
230        let dir = tempfile::tempdir().unwrap();
231        std::fs::write(dir.path().join("compose.yaml"), "services: {}\n").unwrap();
232        let project = Project::open(dir.path(), None).unwrap();
233        assert_eq!(project.variables().unwrap_err().code(), crate::ErrorCode::Unsupported);
234    }
235}