Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added DSCConfigRoot env var in configs #313

Merged
merged 3 commits into from
Feb 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion dsc/src/subcommand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use crate::args::{ConfigSubCommand, DscType, OutputFormat, ResourceSubCommand};
use crate::resource_command::{get_resource, self};
use crate::tablewriter::Table;
use crate::util::{EXIT_DSC_ERROR, EXIT_INVALID_INPUT, EXIT_JSON_ERROR, EXIT_SUCCESS, EXIT_VALIDATION_FAILED, get_schema, write_output, get_input};
use crate::util::{EXIT_DSC_ERROR, EXIT_INVALID_INPUT, EXIT_JSON_ERROR, EXIT_SUCCESS, EXIT_VALIDATION_FAILED, get_schema, write_output, get_input, set_dscconfigroot};
use tracing::error;

use atty::Stream;
Expand Down Expand Up @@ -123,6 +123,8 @@ pub fn config(subcommand: &ConfigSubCommand, parameters: &Option<String>, stdin:
ConfigSubCommand::Test { document, path, .. } |
ConfigSubCommand::Validate { document, path, .. } |
ConfigSubCommand::Export { document, path, .. } => {
let config_path = path.clone().unwrap_or_default();
set_dscconfigroot(&config_path);
get_input(document, stdin, path)
}
};
Expand Down
16 changes: 16 additions & 0 deletions dsc/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ use dsc_lib::{
use schemars::{schema_for, schema::RootSchema};
use serde_yaml::Value;
use std::collections::HashMap;
use std::env;
use std::path::Path;
use std::process::exit;
use syntect::{
easy::HighlightLines,
Expand Down Expand Up @@ -357,3 +359,17 @@ pub fn get_input(input: &Option<String>, stdin: &Option<String>, path: &Option<S

parse_input_to_json(&value)
}

pub fn set_dscconfigroot(config_path: &str)
{
let path = Path::new(config_path);
let config_root = match path.parent()
{
Some(dir_path) => { dir_path.to_str().unwrap_or_default().to_string()},
_ => String::new()
};

// Set env var so child processes (of resources) can use it
debug!("Setting 'DSCConfigRoot' env var as '{}'", config_root);
env::set_var("DSCConfigRoot", config_root.clone());
}
34 changes: 34 additions & 0 deletions dsc_lib/src/functions/envvar.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::DscError;
use crate::configure::context::Context;
use crate::parser::functions::{FunctionArg, FunctionResult};
use super::{Function, AcceptedArgKind};
use std::env;

#[derive(Debug, Default)]
pub struct Envvar {}

impl Function for Envvar {
fn accepted_arg_types(&self) -> Vec<AcceptedArgKind> {
vec![AcceptedArgKind::String]
}

fn min_args(&self) -> usize {
1
}

fn max_args(&self) -> usize {
1
}

fn invoke(&self, args: &[FunctionArg], _context: &Context) -> Result<FunctionResult, DscError> {
let FunctionArg::String(arg) = args.first().unwrap() else {
return Err(DscError::Parser("Invalid argument type".to_string()));
};

let val = env::var(arg).unwrap_or_default();
Ok(FunctionResult::String(val))
}
}
2 changes: 2 additions & 0 deletions dsc_lib/src/functions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::parser::functions::{FunctionArg, FunctionResult};

pub mod base64;
pub mod concat;
pub mod envvar;
pub mod parameters;
pub mod resource_id;

Expand Down Expand Up @@ -53,6 +54,7 @@ impl FunctionDispatcher {
let mut functions: HashMap<String, Box<dyn Function>> = HashMap::new();
functions.insert("base64".to_string(), Box::new(base64::Base64{}));
functions.insert("concat".to_string(), Box::new(concat::Concat{}));
functions.insert("envvar".to_string(), Box::new(envvar::Envvar{}));
functions.insert("parameters".to_string(), Box::new(parameters::Parameters{}));
functions.insert("resourceId".to_string(), Box::new(resource_id::ResourceId{}));
Self {
Expand Down
4 changes: 4 additions & 0 deletions powershellgroup/Tests/PSTestModule/TestClassResource.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ class TestClassResource
{
$this.Prop1 = "ValueForProp1"
}
else
{
$this.Prop1 = $env:DSCConfigRoot
}
$this.EnumProp = [EnumPropEnumeration]::Expected
return $this
}
Expand Down
46 changes: 46 additions & 0 deletions powershellgroup/Tests/powershellgroup.config.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,50 @@ Describe 'PowerShellGroup resource tests' {
$env:PSModulePath = $OldPSModulePath
}
}

It 'DSCConfigRoot macro is working when config is from a file' -Skip:(!$IsWindows){

$yaml = @"
`$schema: https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2023/10/config/document.json
resources:
- name: Working with class-based resources
type: DSC/PowerShellGroup
properties:
resources:
- name: Class-resource Info
type: PSTestModule/TestClassResource
properties:
Name: "[envvar('DSCConfigRoot')]"
"@

$config_path = "$TestDrive/test_config.dsc.yaml"
$yaml | Set-Content -Path $config_path

$out = dsc config get --path $config_path
$LASTEXITCODE | Should -Be 0
$res = $out | ConvertFrom-Json
$res.results[0].result.actualState.Name | Should -Be $TestDrive
$res.results[0].result.actualState.Prop1 | Should -Be $TestDrive
}

It 'DSCConfigRoot macro is empty when config is piped from stdin' -Skip:(!$IsWindows){

$yaml = @"
`$schema: https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2023/10/config/document.json
resources:
- name: Working with class-based resources
type: DSC/PowerShellGroup
properties:
resources:
- name: Class-resource Info
type: PSTestModule/TestClassResource
properties:
Name: "[envvar('DSCConfigRoot')]"
"@
$out = $yaml | dsc config get
$LASTEXITCODE | Should -Be 0
$res = $out | ConvertFrom-Json
$res.results[0].result.actualState.Name | Should -Be ""
$res.results[0].result.actualState.Prop1 | Should -Be ""
}
}
Loading