Ansible中执行curl拉取脚本并运行失败问题排查
Ansible执行Node安装命令报错的原因及解决方法
问题原因
你使用的command模块不支持Shell的管道(|)、逻辑与(&&)这类特殊语法。Ansible的command模块会直接把命令字符串拆分成独立参数传递给执行程序(这里是curl),导致|、&&这些Shell控制字符被当成curl的命令选项,所以出现了curl: option -: is unknown的报错。
解决方法
方法一:改用shell模块
shell模块会通过系统默认Shell(如bash)解析命令,支持管道、逻辑与等语法。同时因为已经设置了become: true,无需重复使用sudo:
- name: Install Node become: true shell: "curl -fsSL https://deb.nodesource.com/setup_19.x | bash - && apt-get install -y nodejs" tags: install_node
方法二:拆分为符合Ansible最佳实践的多任务
将下载脚本、执行脚本、安装软件拆分为独立任务,更清晰且符合幂等性原则(重复执行不会产生意外结果):
- 下载NodeSource的setup脚本
- name: Download NodeSource setup script get_url: url: https://deb.nodesource.com/setup_19.x dest: /tmp/setup_node.sh mode: '0755' tags: install_node
- 执行setup脚本
- name: Run NodeSource setup script become: true command: /tmp/setup_node.sh tags: install_node
- 安装Node.js
- name: Install Node.js become: true apt: name: nodejs state: present update_cache: true tags: install_node
内容的提问来源于stack exchange,提问作者clstaudt
相关产品推荐
相关产品推荐

