我如何指定一个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**

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


当前回答

如需更新

只要运行你的剧本与旗帜-K,他会问你的sudo密码

g.e ansible-playbook你的playbookfile。yaml - k

来自医生

要为sudo指定密码,请运行ansible-playbook和——ask-be -pass (-K)命令

其他回答

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

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

sudo密码存储为名为ansible_sudo_pass的变量。 你可以通过以下几种方式设置这个变量:

对于每个主机,在您的目录hosts文件(inventory/<inventoryname>/hosts)中

[server]
10.0.0.0 ansible_sudo_pass=foobar

每个组,在您的库存组文件(inventory/<inventoryname>/groups)

[server:vars]
ansible_sudo_pass=foobar

每个组,在组vars中(group_vars/<groupname>/ansible.yml)

ansible_sudo_pass: "foobar"

每个组,加密(ansible-vault create group_vars/<groupname>/ansible.yml)

ansible_sudo_pass: "foobar"

Ansible vault已经在这里被建议了几次,但我更喜欢git-crypt加密我的剧本中的敏感文件。如果你使用git来保存你的ansible playbook,这是一个snap。我发现ansible vault的问题是,我不可避免地会遇到我想要使用的文件的加密副本,在我工作之前必须解密它。git-crypt提供了一个更好的工作流程。

https://github.com/AGWA/git-crypt

使用这个,你可以把你的密码放在你的剧本的var中,并把你的剧本标记为一个加密文件。gitattributes,像这样:

 my_playbook.yml filter=git-crypt diff=git-crypt

你的剧本将在Github上透明加密。然后,您只需要在用于运行ansible的主机上安装加密密钥,或者按照文档上的说明使用gpg进行设置。

这里有一个关于像SSH -agent转发SSH密钥一样转发gpg密钥的很好的问答:https://superuser.com/questions/161973/how-can-i-forward-a-gpg-key-via-ssh-agent。

我们也可以在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

我的黑客自动化这是使用一个环境变量,并通过——extralvars =“ansible_become_pass='{{lookup('env', ' ansible_become_pass ')}}'”访问它。

导出一个env变量,但避免bash/shell历史记录(前面有一个空格或其他方法)。例如:

     export ANSIBLE_BECOME_PASS='<your password>'

查找env变量,同时将额外的ansible_become_pass变量传递到ansible-playbook中,例如:

ansible-playbook playbook.yml -i inventories/dev/hosts.yml -u user --extra-vars="ansible_become_pass='{{ lookup('env', 'ANSIBLE_BECOME_PASS') }}'"

好的替代答案:

@toast38coza: simply use a vaulted value for ansible_become_pass. This is decent. However, for the paranoid teams that need to share ansible vault passwords, and execute ansible plays with induvidual accounts, they coudld use the shared vault password to reverse each others operating system password (identiy theft). Arguably, you need to trust your own team? @slm's bash subshell output generated to temp file descriptor and using the @ prefix to read the ansible variable from the file desriptor. Avoids bash history at least. Not sure, but hopefully subshell echo doesn't get caught and exposed in audit logging (e.g. auditd).