如何使用Ansible内置函数Get-AnsibleParam实现YAML变量传入PS脚本$body
Short Answer
Absolutely! Get-AnsibleParam is built specifically for scenarios like this—extracting variables from Ansible's parameter set (including those loaded from YAML files) and safely passing them to PowerShell logic. Let me break down how to make this work step by step, since I know the official docs can feel vague on practical use cases.
How to Implement This
1. Understand What Get-AnsibleParam Does
First, a quick primer: Get-AnsibleParam is an Ansible-built helper for PowerShell modules. It pulls values from the $params hashtable (which contains all variables Ansible passes to your script), handles type validation, required field checks, and default values. It’s far safer than directly accessing hashtable keys because it includes built-in error handling for missing or malformed data.
2. Modify Your PowerShell Script for Ansible
You’ll need to update your script to accept Ansible’s JSON-formatted input, extract variables with Get-AnsibleParam, and assemble the $Body in the JSON format your API expects.
Here’s the updated script:
# Receive and parse Ansible's input (Ansible passes parameters as JSON) $params = $args[0] | ConvertFrom-Json # Extract core required parameters first $Sb_base_uri = Get-AnsibleParam -obj $params -name "Sb_base_uri" -type "str" -required $true $Auth_filename = Get-AnsibleParam -obj $params -name "Auth_filename" -type "str" -required $true $Method = Get-AnsibleParam -obj $params -name "Method" -type "str" -required $true # Extract all task variables from your YAML file $taskType = Get-AnsibleParam -obj $params -name "type" -type "str" $actions = Get-AnsibleParam -obj $params -name "actions" -type "hashtable" $agent = Get-AnsibleParam -obj $params -name "agent" -type "str" $name = Get-AnsibleParam -obj $params -name "name" -type "str" $summary = Get-AnsibleParam -obj $params -name "summary" -type "str" # Assemble $Body as a hashtable, then convert to JSON for the API $Body = @{ type = $taskType actions = $actions agent = $agent name = $name summary = $summary # Add any other fields from your YAML file here } | ConvertTo-Json -Depth 10 # Your existing Connect function (fixed a typo in the namespace) function Stonebranch.Connect { param( [Parameter(Mandatory=$true)] $Sb_uri, [Parameter(Mandatory=$true)] $Auth_filename, [Parameter(Mandatory=$true)] $Method, [Parameter(Mandatory=$false)] $Body ) $basicAuth = Get-Content "C:\$Auth_filename" $headers = @{ "Authorization" = $basicAuth "Content-Type" = "application/json" } $RSP = $null try { if ($Body -eq $null) { $response = Invoke-RestMethod -Uri $Sb_uri -Method $Method -Headers $headers } else { $response = Invoke-RestMethod -Uri $Sb_uri -Method $Method -Headers $headers -Body $Body } return $response } catch { $RSP = $_.Exception.Message return $RSP } } # Your existing Create.Task.Windows function function Stonebranch.Create.Task.Windows { param( [Parameter(Mandatory=$true)] $Sb_base_uri, [Parameter(Mandatory=$true)] $Auth_filename, [Parameter(Mandatory=$true)] $Method, [Parameter(Mandatory=$true)] $Body ) Stonebranch.Connect -SB_uri "$Sb_base_uri/task" -Auth_filename $Auth_filename -Method $Method -Body $Body } # Execute the task creation and return results to Ansible $result = Stonebranch.Create.Task.Windows -Sb_base_uri $Sb_base_uri -Auth_filename $Auth_filename -Method $Method -Body $Body # Ansible requires modules to return JSON output @{ changed = $true result = $result } | ConvertTo-Json
3. Write the Ansible Playbook to Pass Variables
Create a playbook that loads your YAML variables and passes them to the PowerShell script. Here’s an example:
--- - name: Create Stonebranch Windows Task hosts: localhost vars_files: - task_vars.yml # Load your YAML variable file here tasks: - name: Run PowerShell script to create task win_shell: | & .\stonebranch_task_script.ps1 '@{ Sb_base_uri = "{{ sb_base_uri }}" Auth_filename = "{{ auth_filename }}" Method = "POST" type = "{{ type }}" actions = "{{ actions | to_json }}" agent = "{{ agent }}" name = "{{ name }}" summary = "{{ summary }}" # Add any other variables from task_vars.yml here }' args: executable: powershell.exe
Pro Tips
- Simplify Variable Passing: If you don’t want to list every YAML variable individually, pass the entire YAML structure as a single parameter:
# In the PowerShell script $Body = Get-AnsibleParam -obj $params -name "task_vars" -type "hashtable" | ConvertTo-Json -Depth 10# In the playbook vars: task_vars: "{{ lookup('file', 'task_vars.yml') | from_yaml }}" tasks: - name: Run script win_shell: | & .\script.ps1 '@{ Sb_base_uri = "{{ sb_base_uri }}" Auth_filename = "{{ auth_filename }}" Method = "POST" task_vars = "{{ task_vars | to_json }}" }' - Type Validation: Always use the
-typeparameter inGet-AnsibleParamto ensure variables are the correct type (e.g.,strfor strings,hashtablefor nested objects) — this prevents API errors from malformed data. - Depth for JSON: Use
-Depth 10(or higher) withConvertTo-Jsonto avoid truncating nested structures like youractionsarray.
内容的提问来源于stack exchange,提问作者Tung Do

