From c3978fed4be856a4f3540a7dcdaf35a07fd5570b Mon Sep 17 00:00:00 2001 From: Jordan Borean Date: Tue, 2 Jul 2019 12:22:38 +1000 Subject: [PATCH] Load Ansible module_utils for ps_argspec validator (#58571) * Load Ansible module_utils for ps_argspec validator * fix validation for modules without Requires statement * Moved future comment to proper location --- test/sanity/validate-modules/ps_argspec.ps1 | 31 +++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/test/sanity/validate-modules/ps_argspec.ps1 b/test/sanity/validate-modules/ps_argspec.ps1 index d4fef59afb7..35b918c569f 100755 --- a/test/sanity/validate-modules/ps_argspec.ps1 +++ b/test/sanity/validate-modules/ps_argspec.ps1 @@ -49,6 +49,37 @@ Add-Type -TypeDefinition $dummy_ansible_basic $module_code = Get-Content -LiteralPath $module_path -Raw $powershell = [PowerShell]::Create() +$powershell.Runspace.SessionStateProxy.SetVariable("ErrorActionPreference", "Stop") + +# Load the PowerShell module utils as the module may be using them to refer to shared module options +# FUTURE: Lookup utils in the role or collection's module_utils dir based on #AnsibleRequires +$script_requirements = [ScriptBlock]::Create($module_code).Ast.ScriptRequirements +$required_modules = @() +if ($null -ne $script_requirements) { + $required_modules = $script_requirements.RequiredModules +} +foreach ($required_module in $required_modules) { + if (-not $required_module.Name.StartsWith('Ansible.ModuleUtils.')) { + continue + } + + $module_util_path = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($module_path, '..', '..', '..', + 'module_utils', 'powershell', "$($required_module.Name).psm1")) + if (-not (Test-Path -LiteralPath $module_util_path -PathType Leaf)) { + # Failed to find path, just silently ignore for now and hope for the best + continue + } + + $module_util_sb = [ScriptBlock]::Create((Get-Content -LiteralPath $module_util_path -Raw)) + $powershell.AddCommand('New-Module').AddParameters(@{ + Name = $required_module.Name + ScriptBlock = $module_util_sb + }) > $null + $powershell.AddCommand('Import-Module').AddParameter('WarningAction', 'SilentlyContinue') > $null + $powershell.AddCommand('Out-Null').AddStatement() > $null + +} + $powershell.AddScript($module_code) > $null $powershell.Invoke() > $null