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
user1execute any command asuser2on any host matching the sudoers rule, without needing to enter a password. - If you want to restrict to specific commands only, replace
ALLwith the full paths of the allowed commands (e.g.,/usr/bin/nginx, /usr/bin/systemctl restart nginx).
- This lets
- 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 asuser1), 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
suinstead ofsudofor privilege escalation, addbecome_method: suto 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 !requirettyto the sudoers file to bypass this foruser1. - Password Prompt: If you didn’t set
NOPASSWD, you’ll need to add-Kwhen running your playbook to let Ansible prompt for the sudo password (e.g.,ansible-playbook your_playbook.yml -K).
内容的提问来源于stack exchange,提问作者Ashi
相关产品推荐
相关产品推荐

