大网数据广告活动
服务器运维问答

Running Ansible task as a specific user

· 52CE 我爱测

I am trying to run a specific Ansible task as a different user than the one who is running the playbook. My .yml file looks like this: --- - hosts: staging_servers tasks: - name: check user remote_user: someusername shell: whoami…

问题原文

原帖链接 · errata · CC BY-SA 3.0

I am trying to run a specific Ansible task as a different user than the one who is running the playbook. My .yml file looks like this:

---

- hosts: staging_servers
  tasks:    
    - name: check user
      remote_user: someusername
      shell: whoami

Running this task shows me that whoami command returns a different user than I defined in the task (precisely, returns the user which is defined in hosts file called ubuntu).

I also tried to define the task like this:

---

- hosts: staging_servers
  tasks:
    - name: check user
      sudo: yes
      sudo_user: someusername
      shell: whoami

but then I get 'Missing sudo password' error, although there is a line in sudoers file which says someusername ALL=(ALL) NOPASSWD:ALL and issuing commands with sudo on remote machine as someusername doesn't ask me for a password.

So, how can I run the specific task as a different user which is not the user defined in hosts file or root himself?

社区高分解答

原帖链接 · ex-nerd · CC BY-SA 4.0

Note that after Ansible 1.9, the sudo wording was replaced with become, thus

sudo: yes
sudo_user: some_user

becomes (pun intended):

become: yes
become_user: some_user

See more specifics here: https://stackoverflow.com/a/22749788/402727

Also write this before the actual module (e.g. command or shell) you want to execute for it to take effect. At least in my experience it didn't work correctly if I have written become and become_user after the shell module.

- name: Example user change
  become: true
  become_user: '{{ user }}'
  shell: |
    ...

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2015-01-26)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。