viczem / ansible-keepass Goto Github PK
View Code? Open in Web Editor NEWAnsible lookup plugin to fetch data from KeePass file
License: MIT License
Ansible lookup plugin to fetch data from KeePass file
License: MIT License
Firstly, thank you for the implementation of this, it works very nicely. One additional feature that would be nice to have is to have a viczem.keepass.entry
(and maybe even viczem.keepass.database
) module that modify keepass database entries (and databases respectively). This could even be integrated with the lookup to automatically generate the entry if a variable keepass_generate_entry
is defined true.
We're sharing a keepass file on a webserver with authenicated access. Would this lookup plugin support such a setup? Would this work in AWX/AAP/Tower?
Hey
Thanks for keeping this updated!
I have a little problem with the new update. I run Arch and downgraded python-pykeepass to version 4.0.1.
The issue I'm facing is:
KeePass: run socket for /home/dan/.ansible/ansible.kdbx
KeePass: try connect to socket 0/10
KeePass: try connect to socket 1/10
KeePass: send password to '/tmp/ansible-keepass-6d5c20be.sock'
Traceback (most recent call last):
File "/home/dan/.ansible/plugins/lookup/keepass.py", line 364, in <module>
_keepass_socket(args.kdbx, args.key, args.kdbx_sock, args.ttl)
File "/home/dan/.ansible/plugins/lookup/keepass.py", line 203, in _keepass_socket
s.bind(sock_path)
OSError: [Errno 98] Address already in use
KeePass: try connect to socket 1/10
KeePass: send password to '/tmp/ansible-keepass-6d5c20be.sock'
Traceback (most recent call last):
File "/home/dan/.ansible/plugins/lookup/keepass.py", line 364, in <module>
_keepass_socket(args.kdbx, args.key, args.kdbx_sock, args.ttl)
File "/home/dan/.ansible/plugins/lookup/keepass.py", line 203, in _keepass_socket
s.bind(sock_path)
OSError: [Errno 98] Address already in use
...
Traceback (most recent call last):
File "/home/dan/.ansible/plugins/lookup/keepass.py", line 101, in run
stat.S_ISSOCK(os.stat(socket_path).st_mode)
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/ansible-keepass-6d5c20be.sock'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.10/site-packages/ansible/template/__init__.py", line 962, in _lookup
ran = instance.run(loop_terms, variables=self._available_variables, **kwargs)
File "/home/dan/.ansible/plugins/lookup/keepass.py", line 144, in run
raise AnsibleError("KeePass: socket connection failed for %s" % var_dbx)
ansible.errors.AnsibleError: KeePass: socket connection failed for /home/dan/.ansible/ansible.kdbx
...
KeePass: socket connection failed for /home/dan/.ansible/ansible.kdbx
This happend actually just for the first 3-4 targets (randomly) after that it works fine.
Is there anything else I can tweak?
Thanks again.
When using kpsock.py
with a long path to the keepass store, the following error occurs on macOS (and probably also on linux systems):
Traceback (most recent call last):
File "kpsock.py", line 26, in run
s.bind(sock_file)
OSError: AF_UNIX path too long
I just wanted to create a pull request with a solution. Then i realized that there is a downside to my approach (1). So i thought, it would be better to discuss other posibilities.
I think about these two:
/tmp
tempfile.TemporaryDirectory()
) and place socket inside
@viczem what do you think about these two approaches? Do you have any other ideas to solve this?
When using lookup plugin keepass on a group with multiple host, we have a race condition on creating the command process and pipeline socket. Only one host succeed in lookup data in that case, others that are in the race condition failed.
It is due to the following line code that could be walked in a race condition:
ansible-keepass/plugins/lookup/keepass.py
Line 94 in 107fb09
The previous opening file action should be protect by a lock or mutex while the socket file is not actually created
It shall be possible to open the DB with a key file without password.
Currently, it is not possible with this ansible plugin
Both keepass.py and kpsock.py fail with an Attribute error 'bytes' object has no attribute 'encode'
.
Is it maybe because Python 3.7?
Trying to create socket file getting this error, not sure where was wrong
Traceback (most recent call last):
File "kpsock.py", line 195, in
main(kdbx_fpath, password, kdbx_key_fpath, sock_file_path, args.ttl)
File "kpsock.py", line 84, in main
os.remove(sock_fpath)
OSError: [Errno 2] No such file or directory: '/tmp/ansible-keepass.sock'
This one is actually important. If the power is cut and the drive is accessed by a different OS, then the attachments become exposed. Maybe memory-tempfile
would be useful here.
ansible-keepass/plugins/lookup/keepass.py
Line 349 in 237f3a0
With #27 and the move to an ansible galaxy collection we could add more functionality than just lookup.
Your project started as a lookup plugin but it could be more for KeePass.
I've written a module (follows Ansible standard and best practices, used builtin.lineinfile as model) that writes an attachment to the file system (user, group, mode, selinux stuff etc can be set as well).
Would you be interested in adding it to the collection if I create a PR? We need it for a project we have and our deadline is in 2 weeks.
Being able to use ansible-galaxy install viczem.keepass
would be so much easier for us all.
Hi,
i have two machines with that i run ansible-playbooks.
Both a configured the same(i suppose).
On one off them the plugin does not find the entry in a keepass-file.
functioning: pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)
not functioning: pip 21.0.1 from /usr/local/lib/python3.8/dist-packages/pip (python 3.8)
functioning:
ansible 2.10.5
config file = /home/mg/ansible/ansible.cfg
configured module search path = ['/home/mg/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.8/dist-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.8.5 (default, Jan 27 2021, 15:41:15) [GCC 9.3.0]
not functioning:
ansible 2.10.6
config file = /home/mg/ansible-heimserver/ansible.cfg
configured module search path = ['/home/mg/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.8/dist-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0]
functioning:
mg@ansible2:~/ansible$ ll
insgesamt 120K
drwxrwxr-x 10 mg mg 4,0K Feb 28 13:06 .
drwxr-xr-x 8 mg mg 4,0K Feb 15 20:35 ..
-rw-rw-r-- 1 mg mg 438 Feb 20 23:12 ansible.cfg
-rw-rw-r-- 1 mg mg 264 Feb 20 15:44 .ansible-lint
drwxrwxr-x 9 mg mg 4,0K Feb 26 14:21 Archiv
drwxrwxr-x 8 mg mg 4,0K Feb 20 15:46 .git
drwxrwxr-x 3 mg mg 4,0K Feb 6 10:19 .github
-rw-rw-r-- 1 mg mg 137 Feb 13 14:37 .gitignore
-rw-rw-r-- 1 mg mg 2,4K Feb 25 09:44 .gitlab-ci.yml.old
drwxrwxr-x 2 mg mg 4,0K Feb 28 13:26 group_vars
drwxrwxr-x 2 mg mg 4,0K Feb 26 12:25 host_vars
-r-------- 1 mg mg 1,7K Nov 5 20:20 id_rsa_ansible_user
-rw-rw-r-- 1 mg mg 413 Nov 5 20:22 id_rsa_ansible_user_pub
-rw-rw-r-- 1 mg mg 2,1K Feb 28 13:06 inventory
-rw-rw-r-- 1 mg mg 38K Feb 25 13:28 keepass_db.kdbx
drwxrwxr-x 5 mg mg 4,0K Feb 6 10:19 playbooks
drwxrwxr-x 3 mg mg 4,0K Feb 6 10:19 plugins
-rw-rw-r-- 1 mg mg 201 Feb 25 09:48 README.md
-rw-rw-r-- 1 mg mg 334 Feb 20 15:44 .remote-sync.json
drwxrwxr-x 42 mg mg 4,0K Feb 26 14:21 roles
-r-------- 1 mg mg 23 Aug 20 2020 vault-pass.yml
not functioning:
mg@ansible-test:~/ansible-heimserver$ ll
insgesamt 120K
drwxrwxr-x 10 mg mg 4,0K Feb 28 13:33 .
drwxr-xr-x 8 mg mg 4,0K Feb 28 13:43 ..
-rw-rw-r-- 1 mg mg 438 Feb 20 23:12 ansible.cfg
-rw-rw-r-- 1 mg mg 264 Feb 20 15:44 .ansible-lint
drwxrwxr-x 9 mg mg 4,0K Feb 28 13:33 Archiv
drwxrwxr-x 8 mg mg 4,0K Feb 28 13:33 .git
drwxrwxr-x 3 mg mg 4,0K Feb 28 13:33 .github
-rw-rw-r-- 1 mg mg 137 Feb 13 14:37 .gitignore
-rw-rw-r-- 1 mg mg 2,4K Feb 25 09:44 .gitlab-ci.yml.old
drwxrwxr-x 2 mg mg 4,0K Feb 28 13:33 group_vars
drwxrwxr-x 2 mg mg 4,0K Feb 28 13:33 host_vars
-r-------- 1 mg mg 1,7K Nov 5 20:20 id_rsa_ansible_user
-rw-rw-r-- 1 mg mg 413 Nov 5 20:22 id_rsa_ansible_user_pub
-rw-rw-r-- 1 mg mg 2,1K Feb 28 13:07 inventory
-rw-rw-r-- 1 mg mg 38K Feb 25 13:28 keepass_db.kdbx
drwxrwxr-x 5 mg mg 4,0K Feb 28 13:33 playbooks
drwxrwxr-x 3 mg mg 4,0K Feb 28 13:33 plugins
-rw-rw-r-- 1 mg mg 201 Feb 25 09:48 README.md
-rw-rw-r-- 1 mg mg 334 Feb 20 15:44 .remote-sync.json
drwxrwxr-x 42 mg mg 4,0K Feb 28 13:33 roles
-r-------- 1 mg mg 23 Aug 20 2020 vault-pass.yml
ansible-playbook playbooks/base/0_master.yml -i inventory --key-file id_rsa_ansible_user --vault-password-file vault-pass.yml --limit acng-test.grote.lan --tags=postfix -vvvv
https://git.mgrote.net/mg/ansible
TASK [mgrote.postfix : kopiere sasl_passwd] ************************************************************************
fatal: [acng-test.grote.lan]: FAILED! => {"changed": false, "msg": "AnsibleError: An unhandled exception occurred while templating '{{ lookup('keepass', 'postfix_absender_passwort', 'password') }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while running the lookup plugin 'keepass'. Error was a <class 'ansible.errors.AnsibleError'>, original message: Entry 'postfix_absender_passwort' is not found"}
TASK [mgrote.postfix : kopiere sasl_passwd] ************************************************************************
task path: /home/mg/ansible-heimserver/roles/mgrote.postfix/tasks/main.yml:12
<acng-test.grote.lan> ESTABLISH SSH CONNECTION FOR USER: ansible-user
<acng-test.grote.lan> SSH: ansible.cfg set ssh_args: (-C)(-o)(ControlMaster=auto)(-o)(ControlPersist=60s)
<acng-test.grote.lan> SSH: ANSIBLE_PRIVATE_KEY_FILE/private_key_file/ansible_ssh_private_key_file set: (-o)(IdentityFile="/home/mg/ansible-heimserver/id_rsa_ansible_user")
<acng-test.grote.lan> SSH: ansible_password/ansible_ssh_password not set: (-o)(KbdInteractiveAuthentication=no)(-o)(PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey)(-o)(PasswordAuthentication=no)
<acng-test.grote.lan> SSH: ANSIBLE_REMOTE_USER/remote_user/ansible_user/user/-u set: (-o)(User="ansible-user")
<acng-test.grote.lan> SSH: ANSIBLE_TIMEOUT/timeout set: (-o)(ConnectTimeout=10)
<acng-test.grote.lan> SSH: PlayContext set ssh_common_args: (-o StrictHostKeyChecking=no)
<acng-test.grote.lan> SSH: PlayContext set ssh_extra_args: ()
<acng-test.grote.lan> SSH: found only ControlPersist; added ControlPath: (-o)(ControlPath=/home/mg/.ansible/cp/88e71fe24f)
<acng-test.grote.lan> SSH: EXEC ssh -vvv -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mg/ansible-heimserver/id_rsa_ansible_user"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="ansible-user"' -o ConnectTimeout=10 '-o StrictHostKeyChecking=no' -o ControlPath=/home/mg/.ansible/cp/88e71fe24f acng-test.grote.lan '/bin/sh -c '"'"'echo ~ansible-user && sleep 0'"'"''
<acng-test.grote.lan> (0, b'/home/ansible-user\n', b'OpenSSH_8.2p1 Ubuntu-4ubuntu0.1, OpenSSL 1.1.1f 31 Mar 2020\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 19: include /etc/ssh/ssh_config.d/*.conf matched no files\r\ndebug1: /etc/ssh/ssh_config line 21: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug2: mux_client_hello_exchange: master version 4\r\ndebug3: mux_client_forwards: request forwardings: 0 local, 0 remote\r\ndebug3: mux_client_request_session: entering\r\ndebug3: mux_client_request_alive: entering\r\ndebug3: mux_client_request_alive: done pid = 3158\r\ndebug3: mux_client_request_session: session request sent\r\ndebug3: mux_client_read_packet: read header failed: Broken pipe\r\ndebug2: Received exit status from master 0\r\n')
<acng-test.grote.lan> ESTABLISH SSH CONNECTION FOR USER: ansible-user
<acng-test.grote.lan> SSH: ansible.cfg set ssh_args: (-C)(-o)(ControlMaster=auto)(-o)(ControlPersist=60s)
<acng-test.grote.lan> SSH: ANSIBLE_PRIVATE_KEY_FILE/private_key_file/ansible_ssh_private_key_file set: (-o)(IdentityFile="/home/mg/ansible-heimserver/id_rsa_ansible_user")
<acng-test.grote.lan> SSH: ansible_password/ansible_ssh_password not set: (-o)(KbdInteractiveAuthentication=no)(-o)(PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey)(-o)(PasswordAuthentication=no)
<acng-test.grote.lan> SSH: ANSIBLE_REMOTE_USER/remote_user/ansible_user/user/-u set: (-o)(User="ansible-user")
<acng-test.grote.lan> SSH: ANSIBLE_TIMEOUT/timeout set: (-o)(ConnectTimeout=10)
<acng-test.grote.lan> SSH: PlayContext set ssh_common_args: (-o StrictHostKeyChecking=no)
<acng-test.grote.lan> SSH: PlayContext set ssh_extra_args: ()
<acng-test.grote.lan> SSH: found only ControlPersist; added ControlPath: (-o)(ControlPath=/home/mg/.ansible/cp/88e71fe24f)
<acng-test.grote.lan> SSH: EXEC ssh -vvv -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mg/ansible-heimserver/id_rsa_ansible_user"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="ansible-user"' -o ConnectTimeout=10 '-o StrictHostKeyChecking=no' -o ControlPath=/home/mg/.ansible/cp/88e71fe24f acng-test.grote.lan '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo /home/ansible-user/.ansible/tmp `"&& mkdir "` echo /home/ansible-user/.ansible/tmp/ansible-tmp-1614516866.3457766-3435-65558812116214 `" && echo ansible-tmp-1614516866.3457766-3435-65558812116214="` echo /home/ansible-user/.ansible/tmp/ansible-tmp-1614516866.3457766-3435-65558812116214 `" ) && sleep 0'"'"''
<acng-test.grote.lan> (0, b'ansible-tmp-1614516866.3457766-3435-65558812116214=/home/ansible-user/.ansible/tmp/ansible-tmp-1614516866.3457766-3435-65558812116214\n', b'OpenSSH_8.2p1 Ubuntu-4ubuntu0.1, OpenSSL 1.1.1f 31 Mar 2020\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 19: include /etc/ssh/ssh_config.d/*.conf matched no files\r\ndebug1: /etc/ssh/ssh_config line 21: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug2: mux_client_hello_exchange: master version 4\r\ndebug3: mux_client_forwards: request forwardings: 0 local, 0 remote\r\ndebug3: mux_client_request_session: entering\r\ndebug3: mux_client_request_alive: entering\r\ndebug3: mux_client_request_alive: done pid = 3158\r\ndebug3: mux_client_request_session: session request sent\r\ndebug3: mux_client_read_packet: read header failed: Broken pipe\r\ndebug2: Received exit status from master 0\r\n')
looking for "sasl_passwd" at "/home/mg/ansible-heimserver/roles/mgrote.postfix/templates/sasl_passwd"
Keepass: database file /home/mg/ansible-heimserver/keepass_db.kdbx
Keepass: fetch from kdbx file
Found a vault_id (default) in the vaulttext
We have a secret associated with vault id (default), will try to use to decrypt None
Trying to use vault secret=(FileVaultSecret(filename='/home/mg/ansible-heimserver/vault-pass.yml')) id=default to decrypt None
Trying secret FileVaultSecret(filename='/home/mg/ansible-heimserver/vault-pass.yml') for vault_id=default
Decrypt successful with secret=FileVaultSecret(filename='/home/mg/ansible-heimserver/vault-pass.yml') and vault_id=default
<acng-test.grote.lan> ESTABLISH SSH CONNECTION FOR USER: ansible-user
<acng-test.grote.lan> SSH: ansible.cfg set ssh_args: (-C)(-o)(ControlMaster=auto)(-o)(ControlPersist=60s)
<acng-test.grote.lan> SSH: ANSIBLE_PRIVATE_KEY_FILE/private_key_file/ansible_ssh_private_key_file set: (-o)(IdentityFile="/home/mg/ansible-heimserver/id_rsa_ansible_user")
<acng-test.grote.lan> SSH: ansible_password/ansible_ssh_password not set: (-o)(KbdInteractiveAuthentication=no)(-o)(PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey)(-o)(PasswordAuthentication=no)
<acng-test.grote.lan> SSH: ANSIBLE_REMOTE_USER/remote_user/ansible_user/user/-u set: (-o)(User="ansible-user")
<acng-test.grote.lan> SSH: ANSIBLE_TIMEOUT/timeout set: (-o)(ConnectTimeout=10)
<acng-test.grote.lan> SSH: PlayContext set ssh_common_args: (-o StrictHostKeyChecking=no)
<acng-test.grote.lan> SSH: PlayContext set ssh_extra_args: ()
<acng-test.grote.lan> SSH: found only ControlPersist; added ControlPath: (-o)(ControlPath=/home/mg/.ansible/cp/88e71fe24f)
<acng-test.grote.lan> SSH: EXEC ssh -vvv -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mg/ansible-heimserver/id_rsa_ansible_user"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="ansible-user"' -o ConnectTimeout=10 '-o StrictHostKeyChecking=no' -o ControlPath=/home/mg/.ansible/cp/88e71fe24f acng-test.grote.lan '/bin/sh -c '"'"'rm -f -r /home/ansible-user/.ansible/tmp/ansible-tmp-1614516866.3457766-3435-65558812116214/ > /dev/null 2>&1 && sleep 0'"'"''
<acng-test.grote.lan> (0, b'', b'OpenSSH_8.2p1 Ubuntu-4ubuntu0.1, OpenSSL 1.1.1f 31 Mar 2020\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 19: include /etc/ssh/ssh_config.d/*.conf matched no files\r\ndebug1: /etc/ssh/ssh_config line 21: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug2: mux_client_hello_exchange: master version 4\r\ndebug3: mux_client_forwards: request forwardings: 0 local, 0 remote\r\ndebug3: mux_client_request_session: entering\r\ndebug3: mux_client_request_alive: entering\r\ndebug3: mux_client_request_alive: done pid = 3158\r\ndebug3: mux_client_request_session: session request sent\r\ndebug3: mux_client_read_packet: read header failed: Broken pipe\r\ndebug2: Received exit status from master 0\r\n')
fatal: [acng-test.grote.lan]: FAILED! => {
"changed": false,
"msg": "AnsibleError: An unhandled exception occurred while templating '{{ lookup('keepass', 'postfix_absender_passwort', 'password') }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while running the lookup plugin 'keepass'. Error was a <class 'ansible.errors.AnsibleError'>, original message: Entry 'postfix_absender_passwort' is not found"
The lookup of a property with several (multi) lines is an empty string.
It works with pykeepass in interpreter.
Hi , I've been trying to use the example playbook to test the example but i keep getting 'global name 'FileNotFoundError'' error, Below is my playbook content, could you please help identify what could be wrong?
vars:
keepass_dbx : "./example.kdbx"
spam_login: "{{ lookup('keepass', 'spam', 'User Name')}}"
spam_password: "{{ lookup('keepass', 'spam', 'password')}}"
ham_login: "{{ lookup('keepass', 'example/ham', 'User Name') }}"
ham_password: "{{ lookup('keepass','example/ham', 'password')}}"
pork_custom_property: "{{ lookup('keepass', 'example/pork', 'pork_custom_property', true)}}"
pork_all_custom_properties: "{{ lookup('keepass', 'example/pork', '*', true)}}"
tasks:
- debug:
msg: "fetch group: / username: {{ spam_login }} password: {{ spam_password }}"
- debug:
msg: "fetch group: /example/ham username: {{ ham_login }} password: {{ ham_password }}"
- debug:
msg: "fetch group: /example/pork pork_custom: {{ pork_custom_property }}"
- debug:
msg: "fetch group: /example/pork pork_all_custom_properties: {{ pork_all_custom_properties }}"
I was looking quickly at this project, and is it that this lookup creates a socket in the /tmp folder by default?
ansible-keepass/plugins/lookup/keepass.py
Line 415 in 237f3a0
Shouldn't it be creating in /var/run/user/$(uid)/...?
Would it be possible to get multiple entries without opening the keepass file multiple times? Currently it is time consuming when many entries get fetched during one playbook.
Hi,
I'm using this lookup and when I have backslashes, they are automatically escaped when looked up.
Example :
In keepass, I have a slashes-password entry with password : foo\bar\
When I'm looking up with ansible, it comes with escaped backslashes :
TASK [debug] ********************************
ok: [localhost] => {
"lookup('viczem.keepass.keepass', 'slashes-debug', 'password')": "foo\\bar\\"
}
It seems that the only character being escaped automatically. I tried a lot of filters but no matter what, every time it comes out with backslashes.
Due to a relatively complex environment, I want to use multiple KeePass databases. This already works partially using group_vars, but I cannot represent all my combinations yet.
In order to keep the actual database path and password at one place, e.g., the group_vars, I want to override keepass_dbx
keepass_psw
with the intended database depending on the current task.
I have tried it the following way:
role_keepass_db: '/path/to/db.kdbx'
role_keepass_pwd: 'SuperSecretPassword'
keepass_dbx: "{{ role_keepass_db }}"
keepass_psw: "{{ role_keepass_pwd }}"
or
keepass_dbx: "{{ lookup('vars', 'role_keepass_db') }}"
keepass_psw: "{{ lookup('vars', 'role_keepass_pwd') }}"
Neither combination works, and in both cases I receive the following error:
FAILED! => {"msg": "An unhandled exception occurred while running the lookup plugin 'keepass'. Error was a <type 'exceptions.NameError'>, original message: global name 'FileNotFoundError' is not defined"}
A simple when statement verifies that keepass_dbx = role_keepass_db
(same with password).
When running the task with increased verbosity, I see only the message Keepass: fetch from kdbx file
. While a successful run would show:
Keepass: database file /path/to/db.kdbx
Keepass: fetch from kdbx file
KeePass: attr: password in path: test
It appears that os.path.isfile(kp_dbx)
is not properly validating the path when reassigning the variable, I assume a similar problem with the password.
I am currently running Ansible using Python 2.7. As I installed ansible-keepass just last week from master, I assume to run the latest version.
Any help on this issue is appreciated :)
There can potentially be some hiccups if in the task lists you have two lookups of the same attachment with more than the ttl
of the socket in between. In those cases the path variable still points to the temp file location, but in the meantime the database might have been closed, deleting the file.
Alternatively, maybe the attachment lookup can be coupled to a cache plugin so that we can expire it when the database is closed. I am not sure if we can have more than one cache plugin, but there seem to be plugins like aws_ec2
, which I would suspect only target specific variables.
Hello
First of all thanks for your great lookup !
I'm moving close to you regarding an issue i encounter.
I tried to get a file content from your lookup but the only answer i had was the following :
TASK [debug] *******************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "An unhandled exception occurred while running the lookup plugin 'viczem.keepass.keepass'. Error was a <class 'ansible.errors.AnsibleError'>, original message: KeePass: 'attachment 'vlt-02.lan' is not
found for '['Infra', 'PKI', 'Certificates', 'vlt-02.lan']'' has error 'fetch'. KeePass: 'attachment 'vlt-02.lan' is not found for '['Infra', 'PKI', 'Certificates', 'vlt-02.lan']'' has error 'fetch'"}
PLAY RECAP ********************************************************************************************
localhost : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
But i check directly, the file is present.
$ keepassxc-cli show ~/Keepass/Passwords.kdbx /Infra/PKI/Certificates/vlt-02.lan --show-attachments
Password for /home/paul/Sync/Keypass/Passwords.kdbx :
Title: vlt-02.lan
UserName:
Password: PROTECTED
URL:
Notes:
Uuid: {149d5b66-yyyy-xxxx-zzzz-cc95ee4dc88a}
Tags:
Attachments:
cert.pem (1,3 KiB)
vlt-02.key (3,2 KiB)
vlt-02.pem (1,3 KiB)
How can i help you ?
I tried to add a print()
instruction in your lookup and nothing happen. I also tried a raise Exception and it wasn't relevant
I only have this by adding mmore verbosity
exception during Jinja2 execution: Traceback (most recent call last):
File "/home/paul/.ansible/collections/ansible_collections/viczem/keepass/plugins/lookup/keepass.py", line 180, in _send
raise AnsibleError("KeePass: '%s' has error '%s'" % (resp[2], cmd))
ansible.errors.AnsibleError: KeePass: 'attachment 'vlt-02.lan' is not found for '['Infra', 'PKI', 'Certificates', 'vlt-02.lan']'' has error 'fetch'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.11/site-packages/ansible/template/__init__.py", line 831, in _lookup
ran = instance.run(loop_terms, variables=self._available_variables, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/paul/.ansible/collections/ansible_collections/viczem/keepass/plugins/lookup/keepass.py", line 152, in run
return self._send(socket_path, "fetch", terms)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/paul/.ansible/collections/ansible_collections/viczem/keepass/plugins/lookup/keepass.py", line 183, in _send
raise AnsibleError(str(e))
ansible.errors.AnsibleError: KeePass: 'attachment 'vlt-02.lan' is not found for '['Infra', 'PKI', 'Certificates', 'vlt-02.lan']'' has error 'fetch'
Hi,
I am using this plugin to keep all the user information (passwords, ssh keys...) centralised in a kdbx file and is working great.
The only issue I found is with the attachments, that as they are extracted in a temporal local file it is complex to transfer them between hosts.
As normally all the attachments I have are small plain text files, I have done a modification that allows to recover the content of the attachment directly in the variable like:
vars:
content: "{{ lookup('viczem.keepass.keepass', 'example/pork', 'content', 'test.txt')}}"
task:
- debug:
msg: "Content of the file is {{ content }}"
so there are no temporal files created anyplace.
If you think it is useful I can do a PR from my fork
I do not know if it can be useful to add the capacity to specify the encoding or return raw bytes...
Hello
I stored some pem in my keepass as custom properties.
When i get them with your lookup they are truncated.
TASK [debug] ******************************************************************************************
ok: [localhost] => {
"msg": "-----BEGIN CERTIFICATE-----\nZVVQvmPPNh2tNjVONtVHUDaC0+27/K1viwssHlpaEWGcwhZjPtLVXbMVmw0RNjVj\nVGRsZO0TN1HRNjjJFJ50MKWgMJEcLKEyVRS1qTttD2IlqQNrSj0lZGN4ZGVkAQN0\nAQEnSj0lZwN4ZGZkAQN0AQEnZNNjttVvZN0TPFdTFVo3QDRONDHNN4VPQjNjttVX\nN
bVPNDP6CDbq+adhVpo8Q4JH695w3FwranDOFYyTXqI9867Iuelavu11++q81i1O\nIzvTtslgYxB168hlfDtSAobiRTvTSMhymcP0MCEQnY17tUlaFKcfFVO5JyImxJnW\naviGVxWNsNBKSjHOrCrX+Dg15MBWDmHk1FcdG1CvgeJ7wRgYXGiPmTeau1PVnqxH\nONPEDQFjPXtjR/EZMQcgwDzlohVLpeOBEzf6Mfeu0Cj
bqLP76AQCg/xfgLoFX7yv\nP3PMNdO96oGFs0H3zQ350zwayLO4P1fq/6Ob9181++Q/tdrWSnpM+9K7RAKzTNok\ny3OAlfQejGqTHG6dU2SnWGOY9VyIR0fpd9L8NAC/x90S3tjVy/GPMZDqGs6arkX1\n3+MHZ9RDGOgJpkiXg7YULPLzm6IdSFvQZZA+aR2K4NOVc97imDTx2jy5rlXK90HF\nvktbzydQYAUG2S426Aa
r/sjRObp3+dNECEJS1vMiP1x/RAcxqqJ+Q1qVUVKSLvbw\nP3Y2LcBM21+ZiA1eaRR/yK/wMkqiJefmckKyn4lV2ixAOaQJk22iKZOXT2MSPLK1\npeozbnWU5xC+h6IEk0qq8igWceSxkT6eZUtKAWbbGL1mJfdYVfKLJVseT8KhffXM\nFNXzZ+2gfZ0XFf3xUTVxEEj9galq1yqt1HR+QD81dBhUmhW+vjVQNDNOb1xjI
mNI\nOtAIUERRQwNZttc2oUDgZQVhoTShZO0TN1HqQtDJOOGo3OBqnmI4a2L3UISAnf5O\nR85shQNsOtAIU"
}
I didn't see anything in your code which cut the resp
. Maybe ansible does ?
ansible-keepass/plugins/lookup/keepass.py
Line 290 in c1ecea1
Using find_entries
as in https://github.com/libkeepass/pykeepass#finding-entries
Maybe implementing another lookup plugin or maybe there is a way to add this feature in the existing lookup ?
Hey
just ran into this issue:
Error was a <class 'ModuleNotFoundError'>, original message: No module named 'pykeepass.kdbx_parsing'"}
python-pykeepass v4.0.6
is still fine.
Hello,
This plugin has issues when used in parallel. When executed on group of targets, some systemtically fail, always in the same way. Ive tried to debug and manage to improve somehow with samll patch.
TASK [01-ilo-config-initial : Get Interface 1 config] **************************************************************************************************************************************************************
fatal: [US02-P-SVR-ESXI01-i -> localhost]: FAILED! => {"msg": "An unhandled exception occurred while templating '{{ lookup('viczem.keepass.keepass', 'servers-iLo/'+inventory_hostname, 'password') }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while running the lookup plugin 'viczem.keepass.keepass'. Error was a <class 'ansible.errors.AnsibleError'>, original message: KeePass: socket connection failed for /test/keepass.kdbx. KeePass: socket connection failed for /test/keepass.kdbx"}
fatal: [US02-P-SVR-ESXI02-i -> localhost]: FAILED! => {"msg": "An unhandled exception occurred while templating '{{ lookup('viczem.keepass.keepass', 'servers-iLo/'+inventory_hostname, 'password') }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while running the lookup plugin 'viczem.keepass.keepass'. Error was a <class 'ansible.errors.AnsibleError'>, original message: KeePass: socket connection failed for /test/keepass.kdbx. KeePass: socket connection failed for /test/keepass.kdbx"}
fatal: [US02-P-SVR-ESXI03-i -> localhost]: FAILED! => {"msg": "An unhandled exception occurred while templating '{{ lookup('viczem.keepass.keepass', 'servers-iLo/'+inventory_hostname, 'password') }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while running the lookup plugin 'viczem.keepass.keepass'. Error was a <class 'ansible.errors.AnsibleError'>, original message: KeePass: socket connection failed for /test/keepass.kdbx. KeePass: socket connection failed for /test/keepass.kdbx"}
fatal: [US02-M-SVR-ESXI01-i -> localhost]: FAILED! => {"msg": "An unhandled exception occurred while templating '{{ lookup('viczem.keepass.keepass', 'servers-iLo/'+inventory_hostname, 'password') }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while running the lookup plugin 'viczem.keepass.keepass'. Error was a <class 'ansible.errors.AnsibleError'>, original message: KeePass: socket connection failed for /test/keepass.kdbx. KeePass: socket connection failed for /test/keepass.kdbx"}
ok: [US02-P-SVR-ESXI09-i -> localhost]
ok: [US02-P-SVR-ESXI11-i -> localhost]
ok: [US02-M-SVR-ESXI02-i -> localhost]
ok: [US02-P-SVR-ESXI10-i -> localhost]
Ive tried to debug and manage to improve somehow with small retry patch.
TASK [01-ilo-config-initial : Get Interface 1 config] **************************************************************************************************************************************************************
Traceback (most recent call last):
File "/root/.ansible/collections/ansible_collections/viczem/keepass/plugins/lookup/keepass.py", line 441, in <module>
_keepass_socket(kdbx, key, kdbx_sock, args.ttl, password)
File "/root/.ansible/collections/ansible_collections/viczem/keepass/plugins/lookup/keepass.py", line 260, in _keepass_socket
conn.send(
BrokenPipeError: [Errno 32] Broken pipe
fatal: [US02-M-SVR-ESXI02-i -> localhost]: FAILED! => {"msg": "An unhandled exception occurred while templating '{{ lookup('viczem.keepass.keepass', 'servers-iLo/'+inventory_hostname, 'password') }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while running the lookup plugin 'viczem.keepass.keepass'. Error was a <class 'ConnectionRefusedError'>, original message: [Errno 111] Connection refused. [Errno 111] Connection refused"}
fatal: [US02-M-SVR-ESXI01-i -> localhost]: FAILED! => {"msg": "An unhandled exception occurred while templating '{{ lookup('viczem.keepass.keepass', 'servers-iLo/'+inventory_hostname, 'password') }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while running the lookup plugin 'viczem.keepass.keepass'. Error was a <class 'ConnectionRefusedError'>, original message: [Errno 111] Connection refused. [Errno 111] Connection refused"}
ok: [US02-P-SVR-ESXI02-i -> localhost]
ok: [US02-P-SVR-ESXI03-i -> localhost]
ok: [US02-P-SVR-ESXI11-i -> localhost]
ok: [US02-P-SVR-ESXI01-i -> localhost]
ok: [US02-P-SVR-ESXI09-i -> localhost]
ok: [US02-P-SVR-ESXI10-i -> localhost]
--- keepass_orig.py 2022-11-02 17:50:04.000000000 -0400
+++ keepass.py 2022-11-02 17:58:21.000000000 -0400
@@ -123,12 +123,15 @@
success = True
else:
raise AnsibleError("KeePass: wrong dbx password")
+ else:
+ raise
sock.close()
break
except FileNotFoundError:
# wait until the above command open the socket
time.sleep(1)
-
+ except:
+ time.sleep(1)
if not success:
raise AnsibleError("KeePass: socket connection failed for %s" % var_dbx)
@@ -243,7 +246,9 @@
# CMD: fetch
# Read data from decrypted KeePass file
- if cmd != "fetch":
+ if cmd == "password":
+ conn.send(_resp("password", 0))
+ elif cmd != "fetch":
conn.send(_resp("fetch", 1, "unknown command '%s'" % cmd))
break
Any idea how to make this plugin parallel ready?
Thanks
I've added an attachment to my file with certain content:
I read it like this:
- name: Backend postgres vars
ansible.builtin.include_vars:
file: "{{ lookup('viczem.keepass.keepass', 'infrastructure/infisical', 'attachments', 'infisical-postgres.yml') }}"
name: infisical_postgres_env
However I've noticed that whenever I change the attachment in DB, this plugin still reads old value on next run.
I just updated to the new version and the lookup no longer works. So a downgrade to version 3.2.1 is necessary as mentioned in the README.
Are you already aware of the new version/problem?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.