How to Send Password with Special Characters from Ansible to Python Script

ansibleansible-playbookansible-towerpython

I am invoking a python script from ansible playbook. While invoking I am passing the credentials to the python script as arguments. The password has some special characters.

But in Python script, I am receiving the password without the special characters. So password becomes incorrect and I am getting unauthorized error.

I am having this credential in Ansible tower. So I kept the both ansible playbook and python script in Git and running as a job in Ansible tower.

- hosts: localhost
  gather_facts: false
 vars:
  username: '{{ lookup("env","CREDS_TEST_PWD_USERNAME") }}'
  password: '{{ lookup("env","CREDS_TEST_PWD_PASSWORD") }}'
 tasks:

  - debug: var=password
  - name: Invoking python script
    script: python_script.py {{username}} {{password}}
    args:
      executable: python
    register: user_response
    delegate_to: perbhd01

  - debug: var=user_response 

Above is the Ansible playbook which will invoke the python Script. Say the actual username and password is "ADMIN" and "Oracle$123!". But what I am getting in Python script is "ADMIN" and "Oracle123!"

This is how I am retrieving the credentials in python script.

 import requests
 import json
 import warnings
 import sys
 user_name=sys.argv[1]
 password=sys.argv[2]
 print (password +"****from ansible****")

Please let me know if you have any idea on this issue I am facing.

Best Answer

Add one more variable "credential_password" like this and run the playbook. This regex_escape() will help in escaping the special characters.

username: '{{ lookup("env","CREDS_TEST_PWD_USERNAME") }}'
password: '{{ lookup("env","CREDS_TEST_PWD_PASSWORD") }}'
credential_password: "{{ password | regex_escape() }}"