Use Jenkins Credentials to store password for ANSIBLE vault

If you are working with ANSIBLE, you might have came across VAULT like me. Briefly, you can store your secret information (in my case password) in an encypted format. Creating an encrypted file is pretty straight-forward. But I faced bit of thinking process when I wanted to automate the decryption without storing the encryption key/password in git.

USE CASE:

Provision a windows target.
The authentication method is username/password.
my host file looked like this:

[win]
myhostname/ipaddress

[win:vars]
ansible_user=myusername
ansible_password=mysupersecretpassword
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore
I did not want to commit this to git.
I created folder structure group_vars/win/vars.yml group_vars/win/vault.yml
My hosts file is updated and looks like:
[win]
myhostname/ipaddress

[win:vars]
ansible_user=myusername

ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore
Simply removed password from here.
group_vars/win/vars.yml
--- 
ansible_password: "{{ vault_ansible_password }}"
group_vars/win/vars.yml
--- 
vault_ansible_password: mysupersecretpassword
encrypt vault file
ansible-vault encrypt group_vars/win/vars.yml
This will ask for password, keep that in your brain.
This password is used to decrypt the vault. (Read about it on Ansible portal)

Since I have to provision hosts using Jenkins, I can not use ansible option --ask-vault-pass
I planned to use --vault-password-file option but I do not want to push password file to git.
I created a Credential in jenkins (username/password type).
In my pipeline script I used the following snippet to extract and use the password.

withCredentials([usernamePassword(credentialsId: 'get_credentials_id_from_jenkins', passwordVariable: 'vaultpass', usernameVariable: 'vaultuname')]) {
                    
                    sh '''
                    vaultpasswordfile="vault_pass.txt"
                    echo $vaultpass >> $vaultpasswordfile
                    ansible-playbook -i hosts playbook.yml --vault-password-file $vaultpasswordfile
                    '''
                }

You can delete the workspace after this step, this will make sure vault_pass.txt is deleted.
Jenkins logs does not show password text.