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

Ansible 2.4.2.0切换执行用户求助:user1切换到user2失败

Fixing Ansible Permission Error When Switching from user1 to user2

Hey there, let’s work through this permission issue you’re hitting with Ansible 2.4.2.0. The error message tells us that user1 doesn’t have the right privileges on the remote host to switch to user2 using become. Here’s how to resolve this:

Step 1: Configure Sudoers on the Remote Host

The core problem is that user1 isn’t authorized to run commands as user2 via sudo (Ansible’s default become_method). To fix this:

  • Log into the remote host as a user with root access (or use another account that can run sudo visudo).
  • Run visudo (always use this instead of editing the sudoers file directly to avoid syntax errors).
  • Add this line to the file:
    user1 ALL=(user2) NOPASSWD: ALL
    
    • This lets user1 execute any command as user2 on any host matching the sudoers rule, without needing to enter a password.
    • If you want to restrict to specific commands only, replace ALL with the full paths of the allowed commands (e.g., /usr/bin/nginx, /usr/bin/systemctl restart nginx).
  • Save and exit the editor.

Step 2: Verify the Sudo Configuration

Before testing with Ansible, confirm the setup works directly on the remote host:

  • Switch to user1 (or log in as user1), then run:
    sudo -u user2 whoami
    
  • If the output is user2, the sudoers configuration is working correctly.

Step 3: Adjust Your Ansible Playbook (If Needed)

Make sure your playbook has the correct become parameters. Here’s a minimal example to test:

- name: Test switching to user2
  hosts: your_remote_host_group
  remote_user: user1
  become: yes
  become_user: user2
  tasks:
    - name: Check current user
      command: whoami
      register: current_user
    - name: Print current user
      debug:
        msg: "Current user is {{ current_user.stdout }}"
  • If your remote host uses su instead of sudo for privilege escalation, add become_method: su to the play or task level.

Troubleshooting Edge Cases

If you still see errors, check these common issues:

  • Requiretty Restriction: Some sudoers configs require a terminal. Add Defaults:user1 !requiretty to the sudoers file to bypass this for user1.
  • Password Prompt: If you didn’t set NOPASSWD, you’ll need to add -K when running your playbook to let Ansible prompt for the sudo password (e.g., ansible-playbook your_playbook.yml -K).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:59:25