Ansible:没有密码的sudo

Ansible: sudo without password

我想 运行 对没有 sudo 密码的用户 sa1 进行 ansible:

第一次成功:

[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
}

请帮忙!

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

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

您可以通过 运行:

从服务器本身尝试
sudo -u [yourusername] sudo echo "success"

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

默认情况下 ansible 运行s sudo 带有标志:-H -S -n 成为 root。 --non-interactive 是选项 -n 对应的长格式。此选项似乎使 sudo return 成为错误消息,而没有尝试让身份验证模块执行它们的操作。

我设法通过创建一个 ~/.ansible.cfg 来绕过密码错误,其中包含以下几行,用于最相关的 ansible 版本。

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 User Guide.

中找到新样式配置的文档

如果你想要 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'