Skip to content

Commit c3978fe

Browse files
authored
Load Ansible module_utils for ps_argspec validator (ansible#58571)
* Load Ansible module_utils for ps_argspec validator * fix validation for modules without Requires statement * Moved future comment to proper location
1 parent c260721 commit c3978fe

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

test/sanity/validate-modules/ps_argspec.ps1

+31
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,37 @@ Add-Type -TypeDefinition $dummy_ansible_basic
4949
$module_code = Get-Content -LiteralPath $module_path -Raw
5050

5151
$powershell = [PowerShell]::Create()
52+
$powershell.Runspace.SessionStateProxy.SetVariable("ErrorActionPreference", "Stop")
53+
54+
# Load the PowerShell module utils as the module may be using them to refer to shared module options
55+
# FUTURE: Lookup utils in the role or collection's module_utils dir based on #AnsibleRequires
56+
$script_requirements = [ScriptBlock]::Create($module_code).Ast.ScriptRequirements
57+
$required_modules = @()
58+
if ($null -ne $script_requirements) {
59+
$required_modules = $script_requirements.RequiredModules
60+
}
61+
foreach ($required_module in $required_modules) {
62+
if (-not $required_module.Name.StartsWith('Ansible.ModuleUtils.')) {
63+
continue
64+
}
65+
66+
$module_util_path = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($module_path, '..', '..', '..',
67+
'module_utils', 'powershell', "$($required_module.Name).psm1"))
68+
if (-not (Test-Path -LiteralPath $module_util_path -PathType Leaf)) {
69+
# Failed to find path, just silently ignore for now and hope for the best
70+
continue
71+
}
72+
73+
$module_util_sb = [ScriptBlock]::Create((Get-Content -LiteralPath $module_util_path -Raw))
74+
$powershell.AddCommand('New-Module').AddParameters(@{
75+
Name = $required_module.Name
76+
ScriptBlock = $module_util_sb
77+
}) > $null
78+
$powershell.AddCommand('Import-Module').AddParameter('WarningAction', 'SilentlyContinue') > $null
79+
$powershell.AddCommand('Out-Null').AddStatement() > $null
80+
81+
}
82+
5283
$powershell.AddScript($module_code) > $null
5384
$powershell.Invoke() > $null
5485

0 commit comments

Comments
 (0)