- 1 year ago
How to encrypt WIndows password in Jenkins and pass it to an Ansible job?
To securely pass an encrypted Windows password from Jenkins to an Ansible job, you can use the Jenkins Credentials Binding plugin along with Ansible Vault. This approach ensures that the password is encrypted and securely passed to the Ansible playbook.
Here's a step-by-step guide:
Set up Jenkins Credentials Binding:
Install the "Credentials Binding" plugin in Jenkins if you haven't already.
In Jenkins, go to "Manage Jenkins" > "Manage Credentials."
Click on "Global credentials" domain and then click "Add Credentials."
Choose "Username with password" as the kind.
Enter the Windows username in the "Username" field and the corresponding password in the "Password" field.
Optionally, provide an ID for the credentials (e.g., "windows-credentials") and a description.
Click "OK" to save the credentials.
Encrypt the Ansible Vault Password:
Install Ansible on the machine where you will be running the Ansible playbook.
Use the
ansible-vault
command to create an encrypted file that will store the Windows password. Run the following command:bashansible-vault create encrypted_password.yml
Enter a password when prompted. This password will be used to encrypt the file. Save the password securely.
In the editor that opens, add the Windows password variable in the following format:
yamlwindows_password: your_windows_password
Save and close the file. The contents will be encrypted automatically.
Jenkins Job Configuration:
Create a new Jenkins job or open an existing one.
In the job configuration, go to the "Build Environment" section.
Check the "Use secret text(s) or file(s)" checkbox.
Add a new "Username with password" binding.
For "Username Variable," provide a variable name (e.g.,
WINDOWS_USERNAME
).For "Password Variable," choose the credentials ID you set up in step 1 (e.g.,
windows-credentials
).Save the job configuration.
Update Ansible Playbook:
In your Ansible playbook, use the
WINDOWS_USERNAME
variable to retrieve the Windows username.Use the
ansible-vault
command with the--vault-password-file
option to specify the password file you created in step 2. For example:bashansible-playbook playbook.yml --vault-password-file /path/to/vault_password_file
In the playbook, use the
lookup
plugin to retrieve the encrypted Windows password from theencrypted_password.yml
file:yaml- name: Include encrypted password
set_fact:
windows_password: "{{ lookup('file', '/path/to/encrypted_password.yml') }}"
Use the
windows_password
variable in your Ansible tasks to supply the encrypted password.
That's it! Now, when you run the Jenkins job, it will use the encrypted Windows password provided by the Credentials Binding plugin and pass it securely to the Ansible playbook using Ansible Vault.