You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible的vmware_vm_shell模块中向PowerShell脚本传递数组参数

解决Ansible vmware_vm_shell传递PowerShell数组参数的问题

直接在vm_shell_args中写原生PowerShell数组语法会因为Ansible字符串解析和PowerShell语法规则冲突,导致数组无法被正确识别。以下是正确的传递方式:

步骤1:预先构造NIC参数数组

先通过Ansible变量整理好NIC的配置信息,再转换成符合PowerShell语法的数组字符串,避免直接在参数中嵌套复杂语法。

- name: 整理NIC配置列表
  set_fact:
    nic_configs:
      - [ "{{ vm_info.instance.hw_eth0.macaddress }}", "{{ network_primary_ip }}", "{{ network_primary_subnet }}", "{{ network_primary_gateway }}" ]
      - [ "{{ vm_info.instance.hw_eth1.macaddress }}", "{{ network_backup_ip }}", "{{ network_backup_subnet }}", "" ]

- name: 转换为PowerShell兼容的数组字符串
  set_fact:
    nic_ps_array: "@({{ nic_configs | map('join', ', ') | map('regex_replace', '^', '(') | map('regex_replace', '$', ')') | join(', ') }})"

步骤2:在vmware_vm_shell中传递参数

使用quote过滤器对构造好的数组字符串进行转义,确保PowerShell能正确解析整个数组参数:

- name: 执行PowerShell网卡配置脚本
  community.vmware.vmware_vm_shell:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    validate_certs: false
    vm_id: "{{ vm_info.instance.uuid }}"
    vm_shell: "powershell.exe"
    vm_shell_args: "-ExecutionPolicy Bypass -File C:\\scripts\\configure_nic.ps1 -NIC {{ nic_ps_array | quote }}"
    wait_for_process: true
  delegate_to: localhost

补充:PowerShell脚本的参数接收

确保你的PowerShell脚本正确定义数组类型的参数:

param(
    [Parameter(Mandatory=$true)]
    [array]$NIC
)

# 遍历处理每个NIC配置
foreach ($nic in $NIC) {
    $macAddress = $nic[0]
    $ipAddress = $nic[1]
    $subnetMask = $nic[2]
    $gateway = $nic[3]
    # 此处添加网卡配置逻辑
}

内容的提问来源于stack exchange,提问作者Dhananjaya D N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 01:45:59