Programming

Ansible에 sudo 비밀번호를 지정하십시오.

procodes 2020. 5. 9. 17:00
반응형

Ansible에 sudo 비밀번호를 지정하십시오.


비 대화식으로 Ansible에 대한 sudo 비밀번호를 지정하려면 어떻게해야합니까?

다음과 같이 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**

방법이 있습니까? 프로젝트 배포를 최대한 자동화하고 싶습니다.


를 통해 명령 행에서 변수를 전달할 수 있습니다 --extra-vars "name=value". Sudo 비밀번호 변수는 ansible_sudo_pass입니다. 따라서 명령은 다음과 같습니다.

ansible-playbook playbook.yml -i inventory.ini --user=username \
                              --extra-vars "ansible_sudo_pass=yourPassword"

2017 업데이트 : Ansible 2.2.1.0은 이제 var를 사용합니다 ansible_become_pass. 작동하는 것 같습니다.


워드 프로세서는 강력하게 사용하는 대신 일반 텍스트에 sudo는 암호를 설정하고에 추천 --ask-sudo-pass실행할 때 명령 행에ansible-playbook


2016 년 업데이트 :

--ask-sudo-pass사용되지 않는 것으로 표시된 Ansible 2.0 (100 %가 아님) 문서는 이제 --ask-become-pass대신 사용 하는 것이 좋으며 sudo플레이 북 전체 의 사용을 (으)로 교체합니다 become.


scottod가 제공하는 NOPASSWD 솔루션을 사용할 수 없다고 가정하면이 작업을 수행하는 가장 좋은 방법은 Mircea Vutcovici의 솔루션을 Ansible Vault 와 함께 사용하는 것 입니다.

예를 들어 다음과 같은 플레이 북이있을 수 있습니다.

- hosts: all

  vars_files:
    - secret

  tasks:
    - name: Do something as sudo
      service: name=nginx state=restarted
      sudo: yes

여기에 secretsudo 비밀번호를 포함하는 파일 이 포함되어 있습니다.

ansible-vault를 사용하여이 파일의 암호화 된 버전을 만듭니다.

ansible-vault create secret

암호를 묻는 메시지가 표시되면 기본 편집기를 열어 파일을 편집하십시오. 당신은 ansible_sudo_pass여기에 넣을 수 있습니다.

예 : secret:

ansible_sudo_pass: mysudopassword

저장하고 종료합니다. 이제 secretPlaybook을 실행할 때 Ansible에서 해독 할 수 있는 암호화 된 파일이 있습니다. 참고 : 파일을 사용하여 파일을 편집 할 수 있습니다 ansible-vault edit secret( 파일을 만들 때 사용한 암호를 입력하십시오)

퍼즐의 마지막 부분은 파일 --vault-password-file을 해독하는 데 사용할 Ansible을 제공 하는 것입니다 secret.

라는 파일을 작성하고 파일을 vault.txt작성할 때 사용한 비밀번호를 입력 secret하십시오. 비밀번호는 파일에서 한 줄로 저장된 문자열이어야합니다.

Ansible Docs에서 :

.. 다른 사용자가 키에 액세스 할 수없고 소스 제어에 키를 추가하지 않도록 파일에 대한 권한을 확보하십시오.

마지막으로 이제 다음과 같은 방법으로 플레이 북을 실행할 수 있습니다

ansible-playbook playbook.yml -u someuser -i hosts --sudo --vault-password-file=vault.txt 

위의 디렉토리 레이아웃은 다음과 같습니다.

.
|_ playbook.yml
|_ secret
|_ hosts
|_ vault.txt

Ansible Vault에 대한 자세한 내용은 https://docs.ansible.com/playbooks_vault.html을 참조 하십시오.


코드 ( runner/__init__.py)를 보면 인벤토리 파일에서 코드를 설정할 수 있다고 생각합니다.

[whatever]
some-host ansible_sudo_pass='foobar'

ansible.cfg구성 파일에도 일부 조항이 있지만 현재 구현되지 않았습니다 ( constants.py).


ansible이 원하는대로 플래그에 암호를 지정할 수 있다고 생각하지 않습니다. 설정에 어딘가에있을 수 있지만 설정하면 전반적으로 보안을 덜 사용할 수 있으므로 권장하지 않습니다.

대상 시스템에서 사용자를 작성하고 모든 명령 또는 제한된 명령 목록에 비밀번호없는 sudo 권한을 부여하는 것이 가능합니다.

다음 sudo visudo과 같은 줄 을 실행 하고 입력하면 'privilegedUser'사용자는 다음과 같이 실행할 때 비밀번호를 입력하지 않아도됩니다 sudo service xxxx start.

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

sudo는 암호 라는 변수로 저장됩니다 ansible_sudo_pass. 이 변수를 몇 가지 방법으로 설정할 수 있습니다.

호스트 당 인벤토리 호스트 파일 ( inventory/<inventoryname>/hosts)

[server]
10.0.0.0 ansible_sudo_pass=foobar

인벤토리 그룹 파일에서 그룹 별 ( inventory/<inventoryname>/groups)

[server:vars]
ansible_sudo_pass=foobar

그룹 별, 그룹 변수 ( group_vars/<groupname>/ansible.yml)

ansible_sudo_pass: "foobar"

그룹당 암호화 ( ansible-vault create group_vars/<groupname>/ansible.yml)

ansible_sudo_pass: "foobar"

그룹 또는 모든 서버의 비밀번호를 한 번에 설정할 수 있습니다.

[all:vars]
ansible_sudo_pass=default_sudo_password_for_all_hosts

[group1:vars]
ansible_sudo_pass=default_sudo_password_for_group1

나는이 머리카락 위로 머리카락을 찢고 있었고, 이제 내가 원하는 것을하는 해결책을 찾았습니다.

sudo 비밀번호를 포함하는 호스트 당 1 개의 암호화 된 파일

/ etc / ansible / hosts :

[all:vars]
ansible_ssh_connection=ssh ansible_ssh_user=myuser ansible_ssh_private_key_file=~/.ssh/id_rsa

[some_service_group]
node-0
node-1

그런 다음 각 호스트에 대해 다음과 같이 암호화 된 var 파일을 만듭니다.

ansible-vault create /etc/ansible/host_vars/node-0

내용으로

ansible_sudo_pass: "my_sudo_pass_for_host_node-0"

볼트 암호를 구성하는 방법 (--ask-vault-pass를 통해 입력) 또는 cfg에 의한 방법은 귀하에게 달려 있습니다

이를 기반으로 전체 호스트 파일을 암호화 할 수 있다고 생각합니다 ...


더 정통한 방법은 sudo비밀번호를 LastPass 또는 KeePass같은 안전한 저장소에 저장 한 다음 ansible-playbook사용하여 전달 -e@하지만 실제 파일의 내용을 하드 코딩하는 대신 구성 -e@<(...)사용하여 명령을 실행하는 것입니다. 하위 셸을 사용하고 출력 (STDOUT)을 익명 파일 디스크립터로 리디렉션하여 암호를에 효과적으로 제공합니다 -e@<(..).

$ ansible-playbook -i /tmp/hosts pb.yml \
   -e@<(echo "ansible_sudo_pass: $(lpass show folder1/item1 --password)")

위는 몇 가지 일을하고 있습니다.

  • ansible-playbook -i /tmp/hosts pb.yml -분명히 플레이 북을 통해 플레이 북을 실행하는 것
  • $(lpass show folder1/item1 --password)" - runs the LastPass CLI lpass and retrieves the password to use
  • echo "ansible_sudo_pass: ...password..." - takes the string 'ansible_sudo_pass: ' and combines it with the password supplied by lpass
  • -e@<(..) - puts the above together, and connects the subshell of <(...) as a file descriptor for ansible-playbook to consume.

Further improvements

If you'd rather not type that every time you can simply things like so. First create an alias in your .bashrc like so:

$ cat ~/.bashrc
alias asp='echo "ansible_sudo_pass: $(lpass show folder1/item1 --password)"'

Now you can run your playbook like this:

$ ansible-playbook -i /tmp/hosts pb.yml -e@<(asp)

References


If you are comfortable with keeping passwords in plain text files, another option is to use a JSON file with the --extra-vars parameter (be sure to exclude the file from source control):

ansible-playbook --extra-vars "@private_vars.json" playbook.yml 

Ansible has supported this option since 1.3.


you can write sudo password for your playbook in the hosts file like this:

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

Ansible vault has been suggested a couple of times here, but I prefer git-crypt for encrypting sensitive files in my playbooks. If you're using git to keep your ansible playbooks, it's a snap. The problem I've found with ansible vault is that I inevitably end up coming across encrypted copies of the file that I want to work with and have to go decrypt it before I can work. git-crypt offers a nicer workflow IMO.

Using this, you can put your passwords in a var in your playbook, and mark your playbook as an encrypted file in .gitattributes like this:

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

Your playbook will be transparently encrypted on Github. Then you just need to either install your encryption key on the host you use to run ansible, or follow the instruction on the documentation to set it up with gpg.

There's a good Q&A on forwarding gpg keys like your ssh-agent forwards SSH keys here: https://superuser.com/questions/161973/how-can-i-forward-a-gpg-key-via-ssh-agent.


You can use sshpass utility as below,

$ sshpass -p "your pass" ansible pattern -m module -a args \
   -i inventory --ask-sudo-pass

You can use ansible vault which will code your password into encrypted vault. After that you can use variable from vault in playbooks.

Some documentation on ansible vault:
http://docs.ansible.com/playbooks_vault.html

We are using it as vault per environment. To edit vault we have command as:
ansible-vault edit inventories/production/group_vars/all/vault

If you want to call vault variable you have to use ansible-playbook with parameters like:
ansible-playbook -s --vault-password-file=~/.ansible_vault.password

Yes we are storing vault password in local directory in plain text but it's not more dangerous like store root password for every system. Root password is inside vault file or you can have it like sudoers file for your user/group.

I'm recommending to use sudoers file on the server. Here is example for group admin:
%admin ALL=(ALL) NOPASSWD:ALL


Just call your playbook with --extra-vars "become_pass=Password"

become_pass=('ansible_become_password', 'ansible_become_pass')


Using ansible 2.4.1.0 and the following shall work:

[all]
17.26.131.10
17.26.131.11
17.26.131.12
17.26.131.13
17.26.131.14

[all:vars]
ansible_connection=ssh
ansible_user=per
ansible_ssh_pass=per
ansible_sudo_pass=per

And just run the playbook with this inventory as:

ansible-playbook -i inventory copyTest.yml

we Can also Use EXPECT BLOCK in ansible to spawn bash and customize it as per your needs

- 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

Very simple, and only add in the variable file:

Example:

$ vim group_vars/all

And add these:

Ansible_connection: ssh
Ansible_ssh_user: rafael
Ansible_ssh_pass: password123
Ansible_become_pass: password123

Just an addendum, so nobody else goes through the annoyance I recently did:

AFAIK, the best solution is one along the general lines of toast38coza's above. If it makes sense to tie your password files and your playbook together statically, then follow his template with vars_files (or include_vars). If you want to keep them separate, you can supply the vault contents on the command line like so:

ansible-playbook --ask-vault-pass -e@<PATH_TO_VAULT_FILE> <PLAYBOOK_FILE>

That's obvious in retrospect, but here are the gotchas:

  1. That bloody @ sign. If you leave it out, parsing will fail silently, and ansible-playbook will proceed as though you'd never specified the file in the first place.

  2. You must explicitly import the contents of the vault, either with a command-line --extra-vars/-e or within your YAML code. The --ask-vault-pass flag doesn't do anything by itself (besides prompt you for a value which may or may not be used later).

May you include your "@"s and save an hour.


After five years, I can see this is still a very relevant subject. Somewhat mirroring leucos's answer which I find the best in my case, using ansible tools only (without any centralised authentication, tokens or whatever). This assumes you have the same username and the same public key on all servers. If you don't, of course you'd need to be more specific and add the corresponding variables next to the hosts:

[all:vars]
ansible_ssh_user=ansible
ansible_ssh_private_key_file=home/user/.ssh/mykey
[group]
192.168.0.50 ansible_sudo_pass='{{ myserver_sudo }}'

ansible-vault create mypasswd.yml
ansible-vault edit mypasswd.yml

Add:

myserver_sudo: mysecretpassword

Then:

ansible-playbook -i inv.ini my_role.yml --ask-vault --extra-vars '@passwd.yml'

At least this way you don't have to write more the variables which point to the passwords.


Above solution by @toast38coza worked for me; just that sudo: yes is deprecated in Ansible now. Use become and become_user instead.

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

My hack to automate this was to use an environment variable and access it via --extra-vars="ansible_become_pass='{{ lookup('env', 'ANSIBLE_BECOME_PASS') }}'".

Export an env var, but avoid bash/shell history (prepend with a space, or other methods). E.g.:

     export ANSIBLE_BECOME_PASS='<your password>'

Lookup the env var while passing the extra ansible_become_pass variable into the ansible-playbook, E.g.:

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

Good alternate answers:


This worked for me... Created file /etc/sudoers.d/90-init-users file with NOPASSWD

echo "user ALL=(ALL)       NOPASSWD:ALL" > 90-init-users

where "user" is your userid.

참고URL : https://stackoverflow.com/questions/21870083/specify-sudo-password-for-ansible

반응형