Ansible error attempting to decrypt but no vault secrets found

ISSUE TYPE Bug Report COMPONENT NAME ansible-vault ANSIBLE VERSION ansible 2.5.0 CONFIGURATION OS / ENVIRONMENT N/A SUMMARY I have organized my configs into a role based directory structure. Some o...

The ‘ansible-inventory’ failures I mentioned may be a different bug related to ansible-inventory’s use of json/yaml decoders that dont grok vaulted vars.

If that is the case, then it seems to be related to #31141 and #31946

If I disable all the ‘friendly’ top level exception handling so I can get a full traceback,
the ‘ansible-inventory -i hosts —list’ as run against the ‘hosts’ from https://github.com/alikins/ansible-bug-repro/tree/master/vault_sync_decrypt_fail_31620 fails like:

ERROR! Attempting to decrypt but no vault secrets found
Traceback (most recent call last):
  File "/home/adrian/src/ansible/bin/ansible-inventory", line 118, in <module>
    exit_code = cli.run()
  File "/home/adrian/src/ansible/lib/ansible/cli/inventory.py", line 178, in run
    results = self.dump(results)
  File "/home/adrian/src/ansible/lib/ansible/cli/inventory.py", line 195, in dump
    results = jsonify(stuff, sort_keys=True, indent=4)
  File "/home/adrian/src/ansible/lib/ansible/module_utils/basic.py", line 784, in jsonify
    return json.dumps(data, encoding=encoding, default=_json_encode_fallback, **kwargs)
  File "/usr/lib64/python2.7/json/__init__.py", line 251, in dumps
    sort_keys=sort_keys, **kw).encode(obj)
  File "/usr/lib64/python2.7/json/encoder.py", line 209, in encode
    chunks = list(chunks)
  File "/usr/lib64/python2.7/json/encoder.py", line 434, in _iterencode
    for chunk in _iterencode_dict(o, _current_indent_level):
  File "/usr/lib64/python2.7/json/encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib64/python2.7/json/encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib64/python2.7/json/encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib64/python2.7/json/encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib64/python2.7/json/encoder.py", line 442, in _iterencode
    o = _default(o)
  File "/home/adrian/src/ansible/lib/ansible/module_utils/basic.py", line 778, in _json_encode_fallback
    raise TypeError("Cannot json serialize %s" % to_native(obj))
  File "/home/adrian/src/ansible/lib/ansible/module_utils/_text.py", line 149, in to_bytes
    value = str(obj)
  File "/home/adrian/src/ansible/lib/ansible/parsing/yaml/objects.py", line 131, in __str__
    return str(self.data)
  File "/home/adrian/src/ansible/lib/ansible/parsing/yaml/objects.py", line 107, in data
    return self.vault.decrypt(self._ciphertext).decode()
  File "/home/adrian/src/ansible/lib/ansible/parsing/vault/__init__.py", line 660, in decrypt
    plaintext, vault_id = self.decrypt_and_get_vault_id(vaulttext, filename=filename)
  File "/home/adrian/src/ansible/lib/ansible/parsing/vault/__init__.py", line 698, in decrypt_and_get_vault_id
    raise AnsibleVaultError('Attempting to decrypt but no vault secrets found')
ansible.parsing.vault.AnsibleVaultError: Attempting to decrypt but no vault secrets found

How to solve the error attempting to decrypt but no vault secrets found when using an Ansible Vault to store sensitive password content.

November 13, 2022

Access the Complete Video Course and Learn Quick Ansible by 200+ Practical Lessons

Today we’re going to talk about Ansible troubleshooting, specifically about the attempt to decrypt but no vault secrets found error.
I’m Luca Berton and welcome to today’s episode of Ansible Pilot

Link

  • https://docs.ansible.com/ansible/latest/user_guide/vault.html

The Best Resources For Ansible

Video Course

  • Learn Ansible Automation in 250+examples & practical lessons: Learn Ansible with some real-life examples of how to use the most common modules and Ansible Playbook

Printed Book

  • Ansible For VMware by Examples: A Step-by-Step Guide to Automating Your VMware Infrastructure

eBooks

  • Ansible by Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps
  • Ansible For Windows By Examples: 50+ Automation Examples For Windows System Administrator And DevOps
  • Ansible For Linux by Examples: 100+ Automation Examples For Linux System Administrator and DevOps
  • Ansible Linux Filesystem By Examples: 40+ Automation Examples on Linux File and Directory Operation for Modern IT Infrastructure
  • Ansible For Containers and Kubernetes By Examples: 20+ Automation Examples To Automate Containers, Kubernetes and OpenShift
  • Ansible For Security by Examples: 100+ Automation Examples to Automate Security and Verify Compliance for IT Modern Infrastructure
  • Ansible Tips and Tricks: 10+ Ansible Examples to Save Time and Automate More Tasks
  • Ansible Linux Users & Groups By Examples: 20+ Automation Examples on Linux Users and Groups Operation for Modern IT Infrastructure
  • Ansible For PostgreSQL by Examples: 10+ Examples To Automate Your PostgreSQL database
  • Ansible For Amazon Web Services AWS By Examples: 10+ Examples To Automate Your AWS Modern Infrastructure

demo

Live demo of Ansible Vault in Playbook problem and fix the error:

Attempting to decrypt but no vault secrets found.

The best way of talking about Ansible troubleshooting is to jump in a live demo to show you practically the connection failed error and how to solve it!

Every time we would like to use Ansible Vault to store our sensitive information (passwords, access keys, configuration, etc/) encrypted, we need to specify a password for the decryption of the file.
The screen error simply reminds us that the password is incorrect or not specified.
The solution is relatively easy once you understand the underlying Ansible Vault concept.

code

  • playbook_with_vault.yml
---
- name: Playbook with Vault
  hosts: all
  tasks:
    - name: include vault
      ansible.builtin.include_vars:
        file: mypassword.yml

    - name: print variable
      ansible.builtin.debug:
        var: mypassword
  • mypassword.yml
$ANSIBLE_VAULT;1.1;AES256
64306633373430303333623136363833633539376531666131646564633830383330353264633566
3431393662373037663037623533386463306531313435360a643062643065363638353561613738
32343439356138656363333930336636646566376533356131323830663161393533383566316138
3232356363663335610a343233626230373138626263313335623037333963336662323630363562
66396432653737333031643762353130623962323934663566336637653161386563393638333566
6434326465393363363939336433316566353265626364336265

error execution

$ ansible-playbook -i inventory playbook_with_vault.yml   

PLAY [Playbook with Vault] **************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [localhost]

TASK [include vault] ********************************************************************
fatal: [localhost]: FAILED! => {"ansible_facts": {}, "ansible_included_var_files": [], "changed": false, "message": "Attempting to decrypt but no vault secrets found"}

PLAY RECAP ******************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

fix execution

We need to specify the --ask-vault-password or --vault-password-file option of the ansible-playbook tool when using Ansible Vault file.

$ ansible-playbook -i inventory --ask-vault-password playbook_with_vault.yml
Vault password: 

PLAY [Playbook with Vault] **************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [localhost]

TASK [include vault] ********************************************************************
ok: [localhost]

TASK [print variable] *******************************************************************
ok: [localhost] => {
    "mypassword": "mysupersecretpassword"
}

PLAY RECAP ******************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Recap

Now you know better how to troubleshoot the Ansible error: attempting to decrypt but no vault secrets found.

Subscribe to the YouTube channel, Medium, Website, Twitter, and Substack to not miss the next episode of the Ansible Pilot.

Academy

Learn the Ansible automation technology with some real-life examples in my

My book Ansible By Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps

BUY the Complete PDF BOOK to easily Copy and Paste the 250+ Ansible code

Donate

Want to keep this project going? Please donate


Ansible — Resolve «Attempting to decrypt but no vault secrets found»


Let’s say you have a playbook that uses the file module to create /tmp/foo.txt on your managed nodes.

---
- hosts: all
  tasks:
  - file:
      path: /tmp/foo.txt
      state: touch
...

You attempt to run this playbook.

ansible-playbook foo.yml

And ERROR! Attempting to decrypt but no vault secrets found is returned.

PLAY [all]
ERROR! Attempting to decrypt but no vault secrets found

This error can occur when you have a file in the group_vars directory that has been encrypted by the ansible-vault create or ansible-vault edit or ansible-vault encrypt command. For example, let’s say the /usr/local/ansible/group_vars/all/foo.txt file has been encrypted.

/usr/local/ansible/foo.yml
/usr/local/ansible/group_vars/all/foo.txt

In this scenario, it usually a good idea to first ensure the file was encrypted. If so, something like this should be returned.

~]$ cat foo.txt
$ANSIBLE_VAULT;1.2;AES256;test
38626262613533326438383838363032346366643231633838393661633061633830383832643062
6666663233666435636165323038653462343732343264310a616532376238616537613832363565
63336561303230626332326436303830356335343061386333636131386435316633396464353832
3631303831333164610a393266346630313635313831626639303961663330333736393236373032
3062

Then see if you can decrypt the file using the ansible-vault view command.

ansible-vault view foo.txt

You will be prompted to for the vault password.

Vault password:

After providing the valid vault password, the content of the encrypted file will be displayed.

Hello World

If you are able to decrypt the file, one option would be to use the —ask-vault-pass command line flag so that you are prompted for the vault password.

~]# ansible-playbook foo.yml --ask-vault-pass
Vault password:

Or, you could create a hidden file that contains the password, such as .vault_password.txt, and then use the —vault-password-file or —vault-id option on the command line.

ansible-playbook foo.yml --vault-password-file group_vars/all/.vault_password.txt


Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Содержание

  1. Ansible error attempting to decrypt but no vault secrets found
  2. Did you find this article helpful?
  3. Ansible troubleshooting — Attempting to decrypt but no vault secrets found
  4. How to solve the error attempting to decrypt but no vault secrets found when using an Ansible Vault to store sensitive password content.
  5. The Best Resources For Ansible
  6. Video Course
  7. Printed Book
  8. eBooks
  9. error execution
  10. fix execution
  11. Recap
  12. Academy
  13. Donate
  14. Ansible Error: Decryption Failed – How to fix it quickly
  15. Ansible Error: Decryption Failed
  16. Cause and Fix to the error
  17. Conclusion
  18. PREVENT YOUR SERVER FROM CRASHING!
  19. Ansible Vault: Encrypt | Decrypt a String
  20. Encrypt a String using Ansible Vault
  21. Decrypt a String using Ansible Vault
  22. Decrypt using ansible-playbook command
  23. Decrypt using ansible-vault command
  24. Cannot pipe the vault password via stdin ansible-playbook when ran without a tty #30993
  25. Comments

Ansible error attempting to decrypt but no vault secrets found

Let’s say you have a playbook that uses the file module to create /tmp/foo.txt on your managed nodes.

You attempt to run this playbook.

And ERROR! Attempting to decrypt but no vault secrets found is returned.

This error can occur when you have a file in the group_vars directory that has been encrypted by the ansible-vault create or ansible-vault edit or ansible-vault encrypt command. For example, let’s say the /usr/local/ansible/group_vars/all/foo.txt file has been encrypted.

In this scenario, it usually a good idea to first ensure the file was encrypted. If so, something like this should be returned.

Then see if you can decrypt the file using the ansible-vault view command.

You will be prompted to for the vault password.

After providing the valid vault password, the content of the encrypted file will be displayed.

If you are able to decrypt the file, one option would be to use the —ask-vault-pass command line flag so that you are prompted for the vault password.

Or, you could create a hidden file that contains the password, such as .vault_password.txt, and then use the —vault-password-file or —vault-id option on the command line.

Did you find this article helpful?

If so, consider buying me a coffee over at

Источник

Ansible troubleshooting — Attempting to decrypt but no vault secrets found

How to solve the error attempting to decrypt but no vault secrets found when using an Ansible Vault to store sensitive password content.

Please enable JavaScript

Today we’re going to talk about Ansible troubleshooting, specifically about the attempt to decrypt but no vault secrets found error. I’m Luca Berton and welcome to today’s episode of Ansible Pilot

The Best Resources For Ansible

Video Course

Printed Book

eBooks

Live demo of Ansible Vault in Playbook problem and fix the error:

The best way of talking about Ansible troubleshooting is to jump in a live demo to show you practically the connection failed error and how to solve it!

Every time we would like to use Ansible Vault to store our sensitive information (passwords, access keys, configuration, etc/) encrypted, we need to specify a password for the decryption of the file. The screen error simply reminds us that the password is incorrect or not specified. The solution is relatively easy once you understand the underlying Ansible Vault concept.

error execution

fix execution

We need to specify the —ask-vault-password or —vault-password-file option of the ansible-playbook tool when using Ansible Vault file.

Recap

Now you know better how to troubleshoot the Ansible error: attempting to decrypt but no vault secrets found.

Subscribe to the YouTube channel, Medium, Website, Twitter, and Substack to not miss the next episode of the Ansible Pilot.

Academy

Learn the Ansible automation technology with some real-life examples in my

My book Ansible By Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps

Donate

Want to keep this project going? Please donate

Источник

Ansible Error: Decryption Failed – How to fix it quickly

by Nicky Mathew | Jul 5, 2021

Stuck with the Ansible Error: Decryption Failed? We can help you.

It frustrates us to get an error when we try to run an ansible-playbook.

As part of our Server Management Services, we assist our customers with several Ansible queries.

Today, let us see how we can fix this error.

Ansible Error: Decryption Failed

Recently, we had a customer who came across the following error:

With Ansible Vault, we can encrypt files rather than leaving them visible as plaintext in playbooks.

Generally, we use it on sensitive information like passwords, SSL private keys, etc.

By default, to encrypt data, the Ansible vault uses the AES256 algorithm.

File before encryption :

Encryption using Ansible Vault :

Now it is safe to include as a parameter in the ansible-playbook.

In addition, we need to provide a decryption password when we run the ansible-playbook which contains a file encrypted with ansible vault.

Cause and Fix to the error

Moving ahead, let us see the cause and how our Support Techs fix this error.

Generally, we come across this error because the decryption password we provide to ansible is incorrect.

For example, consider a playbook for the encrypted_data.txt file which we used ansible vault to encrypt and copy over to a target machine after decryption.

If we try to run the playbook directly like this:

This will eventually end up in an error.

So, we have to provide the decryption password to the playbook, either as a prompt to the terminal or as a vault file.

We use a convenient way to pass the vault password. The error disappears once we provide the correct password to the ansible controller.

[Need help with the fix? We’d be happy to assist]

Conclusion

To conclude, an incorrect decryption password can lead us to this error. Today, we saw how our Support Techs fix this error for our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

Источник

Ansible Vault: Encrypt | Decrypt a String

Ansible files may often contain different secret strings e.g. passwords, tokens, keys etc., and the good practice is not to store them in a plain text but to encrypt them.

This is especially important if your Ansible files are tracked in a source control system.

This note shows the examples of how to encrypt and decrypt a string using Ansible vault.

Cool Tip: Encrypt files and messages with a password from the Linux command line, using OpenSSL! Read More →

Encrypt a String using Ansible Vault

Use the following syntax to encrypt a string using Ansible vault:

For example, to create a variable user_password with the encrypted string P@$$w0rd , run:

Now you can save this variable with the encrypted string in an inventory, playbook, role, etc. or set it directly in a task, for example:

Decrypt a String using Ansible Vault

If you run a playbook with the encrypted string without specifying a vault password to decrypt it, you will get an Ansible error as follows:

Decrypt using ansible-playbook command

To be prompted for a vault password, execute the ansible-playbook command with a —ask-vault-pass option:

To load the vault password from a file (useful in different automation scenarios), create the vault.txt file with the password that you used to encrypt the string, e.g:

Ensure permissions on the vault.txt are such that no one else can access it and do not add this file to a source control:

Run your playbook with the —vault-password-file option to decrypt the string without being prompted for the password:

Decrypt using ansible-vault command

To decrypt the string without running a playbook:

Note that there should be no spaces in the vault secret string, otherwise you will get:

To decrypt the string without running a playbook non-interactively:

Cool Tip: How to fix the Ansible’s “sudo: a password is required” error! Read more →

Источник

Cannot pipe the vault password via stdin ansible-playbook when ran without a tty #30993

ISSUE TYPE
COMPONENT NAME
ANSIBLE VERSION
CONFIGURATION

DEFAULT_ROLES_PATH(/vagrant/ansible.cfg) = [u’/vagrant/common_roles’, u’/vagrant/<< roles_path >>’]

OS / ENVIRONMENT
SUMMARY

Since version 2.4.0.0 one cannot pipe the vault password via stdin into ansible-playbook anymore

STEPS TO REPRODUCE

This works in version echo «secret_vault_pass» | ansible-playbook deploy_with_vaulted_file.yml —ask-vault-pass

Since version 2.4.0.0 this results in
ERROR! Attempting to decrypt but no vault secrets found

Same happens with the new vault_id parameter:
echo «secret_vault_pass» | ansible-playbook deploy_with_vaulted_file.yml —vault-id @prompt
results in the error:
ERROR! Attempting to decrypt but no vault secrets found

Is this on purpose or is it a bug?

The text was updated successfully, but these errors were encountered:

I can reproduce that.

. doesn’t work in 2.4, but I can’t reproduce the rest.

For me, on 2.4.0.0, I get:

But it also fails on 2.3, 2.2, and 2.1

@sebastianneubauer paste the ‘ansible —version’ and an example output of ansible 2.3 working?

I can reproduce the ‘ERROR! Attempting to decrypt but no vault secrets found’ error with 2.4, if the playbook I am using is vault encrypted.

In this case, ‘ping_noop.yml’ has been vault-encrypted with the password ‘password’

But it also doesn’t work on 2.3:

crazy, in my local bash, similar to you I cannot get this sdtin/echo thing to work also with 2.3. But in Jenkins it works

And this is the snipped from my Jenkinsfile:

So I must admit: maybe it was pure luck that it worked so far for me.
I am fine with closing this bug, as it seems not to be a bug..

But is there a good way to inject the vault password via environment variables? echoing the environment variable into a file and using this seems really to be a very bad workaround. needing a script which reads out the environment variable also feels like a big mess, as I would have to have such a «boilerplate» script in all my ansible projects.

@alikins I think that after the merge of #22756 (Support of multiple vault passwords), the vault password is no longer captured by the Python getpass.getpass «secure password prompt» function.

  • https://github.com/ansible/ansible/pull/22756/files#diff-bdd6c847fae8976ab8a7259d0b583f34L175
  • https://github.com/ansible/ansible/blob/a14d0f3586617f678b2843a25b521243a99cd589/lib/ansible/parsing/vault/__init__.py (no idea, how the interactive prompt is currently done. )

@gildegoma It still uses getpass.getpass() eventually.

https://github.com/ansible/ansible/blob/devel/lib/ansible/parsing/vault/__init__.py#L280 PromptVaultSecret classes uses ansible.utils.display.Display.prompt(private=True) and display.Display.prompt() uses getpass.getpass()

2.4.0 checks if sys.stdin.isatty() to decide if it should show the interactive prompt (eventually via getpass.getpass()). But for cases that aren’t via tty (likely vagrant and jenkins cases), that means it never calls PromptVautlSecret() or getpass.getpass().

But. getpass.getpass() will fallback to reading from stdin if it is not a tty. Since 2.3 will always call getpass.getpass(), it will eventually fallback to stdin via getpass() if there isnt a tty.

Testing against 2.4 without a tty:

But running same command with 2.3 without a tty works as mentioned above:

Fix seems to be just to remove the isatty() check.

Источник

Stuck with the Ansible Error: Decryption Failed? We can help you.

It frustrates us to get an error when we try to run an ansible-playbook.

As part of our Server Management Services, we assist our customers with several Ansible queries.

Today, let us see how we can fix this error.

Ansible Error: Decryption Failed

Recently, we had a customer who came across the following error:

fatal: [server1.lab.com]: FAILED! => {“msg”: “Decryption failed (no vault secrets were found that could decrypt) on /home/bobcares/ansible/encrypted_data.txt”}
fatal: [server1.lab.com]: FAILED! => {“msg”: “A vault password or secret must be specified to decrypt /home/bobcares/ansible/Bobcares/encrypted_data.txt”}

With Ansible Vault, we can encrypt files rather than leaving them visible as plaintext in playbooks.

Generally, we use it on sensitive information like passwords, SSL private keys, etc.

By default, to encrypt data, the Ansible vault uses the AES256 algorithm.

File before encryption :

$> cat encrypted_data.txt
This is an encrypted data

Encryption using Ansible Vault :

$ ansible-vault encrypt encrypted_data.txt
New Vault password:
Confirm New Vault password:
Encryption successful

After Encryption :

$ > cat encrypted_data.txt
$ANSIBLE_VAULT;1.1;AES256
30613332366266623564636132643536646265316132636439326535613939333061376337666433
3831313731303866643765313962323065346565613937650a396162373436306363383934643464
32393037346666303036306365396139383832383632373235323432666638366335623163363539
3530363234656536620a356138366536643164353462613138333664363134303533326566636232
32623530373362396231613230653939393865323639633966616530346261653863

Now it is safe to include as a parameter in the ansible-playbook.

In addition, we need to provide a decryption password when we run the ansible-playbook which contains a file encrypted with ansible vault.

Cause and Fix to the error

Moving ahead, let us see the cause and how our Support Techs fix this error.

Generally, we come across this error because the decryption password we provide to ansible is incorrect.

For example, consider a playbook for the encrypted_data.txt file which we used ansible vault to encrypt and copy over to a target machine after decryption.

vault.yml :

– hosts: server1.lab.com
tasks:
– name: Copying Encrypted file to target machine and decrypting
copy:
src: encrypted_data.txt
dest: /home/decrypted_data.txt

If we try to run the playbook directly like this:

ansible-playbook vault.yml

This will eventually end up in an error.

So, we have to provide the decryption password to the playbook, either as a prompt to the terminal or as a vault file.

ansible-playbook vault.yml –ask-vault-pass ## To prompt for vault password

ansible-playbook vault.yml –vault-password-file /home/bobcares/private/vault_pass.txt ## To automatically read the vault password

We use a convenient way to pass the vault password. The error disappears once we provide the correct password to the ansible controller.

[Need help with the fix? We’d be happy to assist]

Conclusion

To conclude, an incorrect decryption password can lead us to this error. Today, we saw how our Support Techs fix this error for our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Ansible files may often contain different secret strings e.g. passwords, tokens, keys etc., and the good practice is not to store them in a plain text but to encrypt them.

This is especially important if your Ansible files are tracked in a source control system.

This note shows the examples of how to encrypt and decrypt a string using Ansible vault.

Cool Tip: Encrypt files and messages with a password from the Linux command line, using OpenSSL! Read More →

Use the following syntax to encrypt a string using Ansible vault:

$ ansible-vault encrypt_string '<secret_string>' --name '<variable_name>'

For example, to create a variable user_password with the encrypted string P@$$w0rd, run:

$ ansible-vault encrypt_string 'P@$$w0rd' --name 'user_password'
- sample output -
New Vault password: 
Confirm New Vault password: 
user_password: !vault |
            $ANSIBLE_VAULT;1.1;AES256
            6562383862653033303064643838366139363338616266393135323431626265653334
            3839356135353062643637353866643937363366383039640a39396565326662356432
            6434666633663331323836653538396164613137326665666532633037353961656663
            3837
Encryption successful

Now you can save this variable with the encrypted string in an inventory, playbook, role, etc. or set it directly in a task, for example:

# roles/ansible_vault_example/tasks/main.yml
---
- name: "Set variables"
  set_fact:
    user_name: "admin"
    user_password: !vault |
                $ANSIBLE_VAULT;1.1;AES256
                6562383862653033303064643838366139363338616266393135323431626265653334
                3839356135353062643637353866643937363366383039640a39396565326662356432
                6434666633663331323836653538396164613137326665666532633037353961656663
                3837

- debug:
    msg: "The user '{{ user_name }}' has a password '{{ user_password }}'"

Decrypt a String using Ansible Vault

If you run a playbook with the encrypted string without specifying a vault password to decrypt it, you will get an Ansible error as follows:

TASK [ansible_vault_example : Set variables] ****************************************
fatal: [127.0.0.1]: FAILED! => 
  msg: Attempting to decrypt but no vault secrets found

Decrypt using ansible-playbook command

To be prompted for a vault password, execute the ansible-playbook command with a --ask-vault-pass option:

$ ansible-playbook playbook.yml -i inventory.ini --ask-vault-pass

To load the vault password from a file (useful in different automation scenarios), create the vault.txt file with the password that you used to encrypt the string, e.g:

$ echo "vaultPassw0rd" > vault.txt

Ensure permissions on the vault.txt are such that no one else can access it and do not add this file to a source control:

$ chmod 600 vault.txt
$ echo "vault.txt" >> .gitignore

Run your playbook with the --vault-password-file option to decrypt the string without being prompted for the password:

$ ansible-playbook playbook.yml -i inventory.ini --vault-password-file=vault.txt

Decrypt using ansible-vault command

To decrypt the string without running a playbook:

$ ansible-vault decrypt
- sample output -
Vault password: 
Reading ciphertext input from stdin
$ANSIBLE_VAULT;1.1;AES256
6562383862653033303064643838366139363338616266393135323431626265653334
3839356135353062643637353866643937363366383039640a39396565326662356432
6434666633663331323836653538396164613137326665666532633037353961656663
3837 Enter, Ctrl + D
Decryption successful
P@$$w0rd

Note that there should be no spaces in the vault secret string, otherwise you will get:

ERROR! Vault format unhexlify error: Non-hexadecimal digit found for -

To decrypt the string without running a playbook non-interactively:

$ echo '$ANSIBLE_VAULT;1.1;AES256
6562383862653033303064643838366139363338616266393135323431626265653334
3839356135353062643637353866643937363366383039640a39396565326662356432
6434666633663331323836653538396164613137326665666532633037353961656663
3837 | ansible-vault decrypt --vault-password-file=vault.txt

Cool Tip: How to fix the Ansible’s “sudo: a password is required” error! Read more →

There will be scenarios when we need to supply passwords or access tokens within our Ansible playbooks or as part of Ansible Roles in variable files. Those will be present in cleartext and that poses a greater security risk.

Common types of «secret» which we use are passwords, SSH keys, SSL certs, API access tokens etc.

Ansible Vault allows us to encrypt variables and other files which contains sensitive content such as passwords or keys by providing a vault password.

To use Ansible Vault you need one or more passwords to encrypt and decrypt content. You can use any third-party tool such as a secret manager to store your vault passwords and can access them using a script.

Let us start some practical stuff.

I have a playbook here which creates an user account for a new joinee in our company and copies his/her Non Disclosure Agreement and his SSO credentials to his home directory.

---
- hosts: worker1
  become: yes
  tasks:
  - name: Create user account for Alice
    user:
      name: Alice
      comment: "Alice"
      shell: /bin/bash
      createhome: yes
      home: /home/Alice

  - name: A non-disclosure agreement
    copy:
      content: "This is an Agreement between Alice and the employer LearnCodeOnline. The Agreement is effective on your first day of employment with the Company.n"
      dest: /home/Alice/Agreement

  - name: SSO Credentials
    copy:
      content: Alice@124!
      dest: /home/Alice/sso_creds

Now the problem here is our playbook contains the critical and confidential information which can be read by anyone who has access to our content repository. We want to protect this.

Encrypt an existing playbook or variable file

The command to encrypt an existing playbook or variable file is ansible-vault encrypt.
It will prompt for providing vault password. This command can operate on multiple files at once.

vault $ ansible-vault encrypt user_creds.yml
New Vault password:
Confirm New Vault password:
Encryption successful

That’s done, the file is now encrypted! Now If you try to edit the file directly, you’ll just see encrypted text.

The default cipher is AES (which is shared-secret based).

vault $ cat user_creds.yml
$ANSIBLE_VAULT;1.1;AES256
61323636356165363839303366333232646431666537346330323966316464633935636564363434
6230306139303732373336646239343462373061386362620a396164336466366231633830333265
33353039393463333236653462323664346533343333623434376334343536323366393066636362
6363653435393266380a653863316366326262653539313430353737346530646364303966353661
38373061323336363830303236613863623637373533373636646161623461623533313034656166
36613436393262343466376362353131323163386632393538663534633538396133653333333865
32396535323837613265626430366130666135333438613864303133393063633033386364643866
30623130396331613539376639316566373737336265323939646366366134663632396230643436
33386231363764633262633565623635346137303462393437656261323634316133616634303332

Create a vault-encrypted file

To create a new playbook/variable file encrypted with Vault, you should use the ansible-vault create command. It will then open the file in your default text editor. You enter your data there and save & quit.

vault $ ansible-vault create vault_test.yml
New Vault password:
Confirm New Vault password:

Viewing an encrypted playbook or variable file

If you want to view an encrypted file, use the ansible-vault view command as shown below. You will have to provide the vault password in order to view it.

vault $ ansible-vault view user_creds.yml
Vault password:

VAULT-VIEW.png

Editing an encrypted playbook or variable file

If you want to edit an encrypted file, use the ansible-vault edit command as shown below. You will have to provide the vault password in order to view it.

vault $ ansible-vault edit user_creds.yml
Vault password:

VAULT-edit.png

Run an encrypted playbook file

Once a playbook file is encrypted you will not be able to run that as usual.

You will get an error as below.

vault $ ansible-playbook -i myinventory user_creds.yml -kK
SSH password:
BECOME password[defaults to SSH password]:
ERROR! Attempting to decrypt but no vault secrets found

There are two methods to run an encrypted file.

Method 1: Use --ask-vault-pass flag

By using the --ask-vault-pass flag Ansible will ask for the vault password so the playbook file can be decrypted correctly.

vault $ ansible-playbook -i myinventory user_creds.yml --ask-vault-pass -kK
SSH password:
BECOME password[defaults to SSH password]:
Vault password:

VAULT-ask-vault-pass.png

Method 2: Use --vault-password-file flag
Providing vault password every time is annoying at times and not a feasible solution as well. And that makes our automation process as well These prompts make automation unsustainable.

To fix that we need a mechanism which decrypts playbooks during runtime, and that can be achieved by having a separate password file that contains the Ansible vault password and can be passed at run time.

vault $ ansible-playbook -i myinventory user_creds.yml --vault-password-file /home/ansible_user/.ansible_vault_pass -kK
SSH password:
BECOME password[defaults to SSH password]:

VAULT-vault-pass-file.png

Change Ansible Vault Password

If you want change the Ansible vault password, it can be done easily by using ansible-vault rekey command as shown below.

vault $ ansible-vault rekey user_creds.yml
Vault password:
New Vault password:
Confirm New Vault password:
Rekey successful

Decrypting an encrypted playbook or variable file

If you want to decrypt an encrypted file, use the ansible-vault decrypt command as shown below. You will have to provide the vault password in order to view it.

vault $ ansible-vault decrypt user_creds.yml
Vault password:
Decryption successful

Now you can view the content of that file by a simple cat command.

VAULT-decrypt.png

Encrypt specific variables

With Ansible Vault we can encrypt specific variables as well. We no need to encrypt the whole playbook or variable files all the time.

This helps us in better tracking of version changes on Git as even just opening an encrypted file changes the encrypted hash.

Here are the commands to encrypt specific variables aka strings.

vault $ ansible-vault encrypt_string 'Alice@124!' --name 'alice_sso'
New Vault password:
Confirm New Vault password:
alice_sso: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          66333766346464633037666164326163343235386538373265346133396162643934373862623765
          6235323762323137393661626331303938646162646666610a353365373332306661646461366237
          37626363656232316563363162336339323937623931623735643931623635343963633737313832
          6333303730346633610a393134646462626662636438623830316536656436306139616566313136
          3139
Encryption successful

You can see from the above output that the password has been encrypted with AES 256 encryption.

Now the question is how to use this encrypted output in our playbook.

To do that copy the entire encrypted code starting from !vault |. Go and edit your playbook file and put this encrypted block instead of the plain text password.

vault $ cat user_creds.yml
---
- hosts: worker1
  become: yes
  vars:
    alice_sso: !vault |
       $ANSIBLE_VAULT;1.1;AES256
       66333766346464633037666164326163343235386538373265346133396162643934373862623765
       6235323762323137393661626331303938646162646666610a353365373332306661646461366237
       37626363656232316563363162336339323937623931623735643931623635343963633737313832
       6333303730346633610a393134646462626662636438623830316536656436306139616566313136
       3139
  tasks:
  - name: Create user account for Alice
    user:
      name: Alice
      comment: "Alice"
      shell: /bin/bash
      createhome: yes
      home: /home/Alice

  - name: A non-disclosure agreement
    copy:
      content: "This is an Agreement between Alice and the employer LearnCodeOnline. The Agreement is effective on your first day of employment with the Company.n"
      dest: /home/Alice/Agreement

  - name: SSO Credentials
    copy:
      content: "{{ alice_sso }}"
      dest: /home/Alice/sso_creds

Let us execute the playbook.

vault $ ansible-playbook -i myinventory user_creds.yml -kK --ask-vault-pass
SSH password:
BECOME password[defaults to SSH password]:
Vault password:

VAULT-vault-encrypt-string-2.png

It seems to be successful. Now verify the content if copied properly.

vault $ ansible -i myinventory worker1 -m shell -a "cat /home/Alice/sso_creds" -b -kK
SSH password:
BECOME password[defaults to SSH password]:
worker1 | CHANGED | rc=0 >>
Alice@124!

Great! It has copied the content as expected.

Ansible Vault Best Practices

Security is very crucial part these days and keeping passwords protected should be the most important thing while working on any project. Below are several best practices to use when utilizing Ansible Vault.

  1. ACL should be implemented on Password files : Make sure that only the appropriate users can access the password file.
  2. Password Files should never be kept within version control systems, such as GIT or Subversion. Store them in some external secure vaults. Such as Hashicorp’s vault etc.
  3. Always use separate vaults : Normally, many different environments are in use. Therefore, it is best to separate the required credentials into the appropriate vaults.
  4. Frequent Rekeying : You should regularly rekey the vault passwords as it might leak while reuses. It limits the exposure.
  5. Keep a proper naming convention to use secrets! A suggestion would be to name all variables stored in the ansible vault with a secret_ prefix.

That’s all for this article.

Hope you like the article. Stay Tuned for more.

Thank you. Happy learning!

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Another version of this product is already installed как исправить
  • Another launcher is already running как исправить
  • Another instance of this program is already running error
  • Another instance is already running как исправить ошибку
  • Another instance is already running euro truck simulator 2 как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии