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

Ansible playbook开启become:yes后执行失败,配置sudo密码仍报错如何解决

问题根因
  • 你在play层级全局配置了become: yes,该规则会作用于所有任务,包括你设置了delegate_to: localhost的读取本地CSV文件的任务
  • inventory中配置的ansible_sudo_pass是远程目标主机的sudo凭证,不会生效于你的Ansible控制节点(也就是localhost)
  • 读取本地policy.csv的任务本身不需要root权限,全局提权配置触发了本地sudo验证,又没有对应的本地sudo凭证,因此产生报错。

你之前尝试的--ask-become-pass参数输入的密码默认仅作用于远程目标主机,不会用于本地提权验证,因此无法解决问题。

解决方案

方案1:取消全局提权配置,仅在需要提权的远程任务单独配置

将play层级的become: yes移除,在需要远程提权执行的两个任务上单独添加提权配置:

---
- hosts: all
  tasks:
    - name: Register the policy file in a variable
      read_csv:
        path: policy.csv
      delegate_to: localhost
      register: csv_file

    - name: Check rules pre-remediation
      command: "{{ item.Compliance_check }}"
      register: output 
      with_items: "{{ csv_file.list }}"
      become: yes  # 仅该任务远程提权

    - name: Perform remediation
      command: "{{ item.item.Remediation }}"
      when: item.item.Expected_result != item.stdout
      with_items: "{{ output.results }}"
      become: yes  # 仅该任务远程提权

方案2:给本地委派任务单独关闭提权

保留全局become: yes配置,给读取CSV的本地任务单独添加become: no覆盖全局规则:

- name: Register the policy file in a variable
  read_csv:
    path: policy.csv
  delegate_to: localhost
  register: csv_file
  become: no  # 本地任务不需要提权,覆盖全局配置

方案3(仅适用于本地确实需要提权的场景)

如果你的本地读取CSV操作确实需要root权限,可以在inventory中添加localhost的提权凭证配置:

localhost ansible_become_pass=你的控制节点sudo密码
10.136.59.110 ansible_ssh_user=username ansible_ssh_pass=password ansible_sudo_pass=password

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:36:05