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

Ansible:如何结合expect模块使用yum命令?执行报错求助

问题解决步骤

1. 修正任务变量引用

第一个任务中,unpatch.stdout_lines是列表类型,直接传入yum命令会导致格式错误(比如变成yum history undo ['123']),应该改用unpatch.stdout(因为shell命令返回的是单个ID,stdout就是该ID的字符串),或者unpatch.stdout_lines[0]明确取第一个元素。

修正后的变量引用示例:

command: yum history undo {{ unpatch.stdout }}

2. 修复expect模块的responses格式错误

原配置中responses的写法是字符串而非字典,Ansible要求responses是键值对字典:键是匹配交互提示的正则表达式,值是要发送的响应内容。

正确的responses配置如下:

responses:
  'Is this ok \[y/d/N\]:': 'y'
  • 正则表达式用单引号包裹,转义[和](因为它们在正则中是特殊字符)
  • 键对应yum的交互提示文本,值是要输入的确认指令y

3. 更简单的替代方案:跳过yum交互

实际上yum history undo支持-y参数直接确认操作,完全不需要使用expect模块,这是更可靠且简洁的方式:

- name: Unpatch server to N-1 level
  become: yes
  shell: yum history undo {{ unpatch.stdout }} -y

完整修正后的Playbook

- name: Find "N-1" unpatching ID from the Yum History
  become: yes
  shell: yum history | head -n -3 | tail -n +5 | awk '{print $1}' | head -n 1
  register: unpatch
        
- name: Unpatch server to N-1 level (using yum -y)
  become: yes
  shell: yum history undo {{ unpatch.stdout }} -y

错误原因解析

  • 第一个错误:responses参数被写成字符串,而Ansible要求其为字典类型,导致参数解析失败。
  • 第二个错误:将responses设为yes不符合参数格式,expect模块无法正确匹配yum的交互提示,导致进程挂起等待输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 13:52:28