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

如何将Bash脚本中的字符串数组传递给Ansible playbook并遍历输出

修复方案

1. 修正Bash脚本的传参逻辑

原脚本存在两处核心错误:

  • 直接调用$ntpServers仅能获取数组第一个元素,无法传递完整数组
  • --extra-vars参数的键值对不允许加空格,否则Ansible无法识别变量名,这也是你收到ntp_list is undefined报错的直接原因
    修正后的Bash函数代码(需要将数组转换为Ansible可识别的JSON列表格式):
configureChrony() {
  ntpServer="initVal"
  ntpServers=()
  while ! [[ -z "$ntpServer" ]]; do
    read -e -p "Please input the ip address or domain name of the NTP server you wish to add: " ntpServer
    if ! [[ -z "$ntpServer" ]]; then
      ntpServers+=("$ntpServer")
    fi
  done

  # 转换Bash数组为JSON格式列表,依赖jq工具(通用Linux发行版可直接通过包管理器安装)
  ntp_list_json=$(printf '%s\n' "${ntpServers[@]}" | jq -R . | jq -s .)
  ansible-playbook -i localhost, test.yml --extra-vars="ntp_list=$ntp_list_json"
}

如果环境无jq工具,可使用手动拼接方案替换JSON生成逻辑:

# 手动拼接JSON数组,无需依赖第三方工具
ntp_list_json='['
for server in "${ntpServers[@]}"; do
  ntp_list_json+="\"$server\","
done
ntp_list_json="${ntp_list_json%,}]"

2. 修正Ansible Playbook遍历逻辑

原Playbook存在两处遍历错误:

  • ntp_list是字符串数组,每个元素没有name属性,直接输出{{ item }}即可
  • with_items后不需要额外加短横线,否则会将整个数组当成单元素列表遍历
    修正后的test.yml代码:
---
- name: "This is a test"
  hosts: all
  gather_facts: no
  tasks:
    - name: print variable - with_items
      debug:
        msg: "{{ item }}"
      with_items: "{{ ntp_list }}"

修改完成后即可正常遍历输出所有输入的NTP服务器地址。

内容的提问来源于stack exchange,提问作者Ruth Edges

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:54:07