我如何指定一个sudo密码Ansible在非交互的方式?

我是这样运行Ansible剧本的:

$ ansible-playbook playbook.yml -i inventory.ini \
    --user=username --ask-sudo-pass

但我想这样运行它:

$ ansible-playbook playbook.yml -i inventory.ini \
    --user=username` **--sudo-pass=12345**

有办法吗?我希望尽可能地自动化我的项目部署。


当前回答

您可以为一个组或所有服务器设置密码:

[all:vars]
ansible_sudo_pass=default_sudo_password_for_all_hosts

[group1:vars]
ansible_sudo_pass=default_sudo_password_for_group1

其他回答

你可以像这样在hosts文件中为你的剧本写sudo密码:

[host-group-name]
host-name:port ansible_sudo_pass='*your-sudo-password*'

我不认为ansible会让你在标志中指定密码,因为你希望这样做。 可能在配置的某个地方可以设置这个,但这将使使用ansible整体不太安全,不建议使用。

您可以做的一件事是在目标计算机上创建一个用户,并向其授予所有命令或受限制的命令列表的无密码sudo特权。

如果你运行sudo visudo并输入如下一行,那么用户'privilegedUser'在运行sudo service xxxx start时应该不需要输入密码:

%privilegedUser ALL= NOPASSWD: /usr/bin/service

如果您正在使用密码管理器,您可以使用模块passwordstore,这使得这非常容易。

假设您将用户的sudo密码保存为pass as

服务器 1/用户

然后您可以像这样使用解密后的值

{{ lookup('community.general.passwordstore', 'Server1/User')}}"

我在我的清单中使用它:

---
   servers:
     hosts:
       server1:
         ansible_become_pass: "{{ lookup('community.general.passwordstore', 'Server1/User')}}"

请注意,您应该运行gpg-agent,这样您就不会在每次运行“成为”任务时看到pinentry提示。

我们也可以在ansible中使用EXPECT BLOCK来生成bash并根据您的需要自定义它

- name: Run expect to INSTALL TA
  shell: |
    set timeout 100
    spawn /bin/sh -i

    expect -re "$ "
    send "sudo yum remove -y xyz\n"

    expect "$ "
    send "sudo yum localinstall -y {{ rpm_remotehost_path_for_xyz }}\n"

    expect "~]$ "
    send "\n"

    exit 0
  args:
  executable: /usr/bin/expect

以上@toast38coza的解决方案对我来说很管用;只是sudo: yes现在在Ansible中被弃用了。 请使用become和become_user。

tasks:
 - name: Restart apache service
   service: name=apache2 state=restarted
   become: yes
   become_user: root