Ansible:无需密码的 sudo

问题描述 投票:0回答:3

我想用用户 sa1 运行 ansible 而无需 sudo 密码:

第一次OK:

[root@centos1 cp]# ansible cent2 -m shell -a "sudo yum -y install httpd"

cent2 | SUCCESS | rc=0 >>

第二次失败:

[root@centos1 cp]# ansible cent2 -s -m yum -a "name=httpd state=absent"

cent2 | FAILED! => {
    "changed": false,
    "failed": true,
    "module_stderr": "",
    "module_stdout": "sudo: a password is required\r\n",
    "msg": "MODULE FAILURE",
    "parsed": false
}

请帮忙!

linux ansible sudo
3个回答
15
投票

这不是ansible,而是您服务器的配置。确保 ansible 正在使用的用户无需密码即可使用 sudo。

  1. 为此,请登录服务器
  2. 使用
    sudo visudo
  3. 打开 sudoers 文件
  4. 确保你有这样一行:
    centos ALL=(ALL) NOPASSWD:ALL
  5. centos
    替换为您的用户
  6. 保存文件

您可以通过运行从服务器本身尝试:

sudo -u [yourusername] sudo echo "success"

如果这有效,它也应该可以在 ansible 中工作。


10
投票

默认情况下,ansible 使用以下标志运行 sudo:

-H -S -n
以成为 root。其中
--non-interactive
是选项
-n
对应的长形式。此选项似乎使 sudo 返回错误消息,而不尝试让身份验证模块执行其操作。

对于最相关的 ansible 版本,我通过创建包含以下行的 ~/.ansible.cfg 设法解决了密码错误。

ansible 2.4

[defaults]
sudo_flags = --set-home --stdin

ansible 2.9

[sudo_become_plugin]
flags = -H -S

这至少足以允许 pam_ssh_agent_auth.so 运行并对我进行身份验证。

在 2.8 版本之前,上面的示例可以工作,2.8 之后的版本需要第二个示例。新样式配置的文档可以在Ansible 用户指南中找到。


8
投票

这是剧本,以防您想要 ansible 为您制作

  1. 将用户添加到所选组(在我的例子中
    wheel
  2. 将此添加到您的剧本中
- name: Make users passwordless for sudo in group wheel
  lineinfile:
    path: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'
© www.soinside.com 2019 - 2024. All rights reserved.