I would need to extract an username and a password from a configuration file.
define( 'DB_USER', 'username' );
define( 'DB_PASSWORD', 'password' );
So far I managed to extract a string, using this code:
- set_fact:
dbuser: "{{ wpconfig.stdout | regex_search('DB_USER(.+)', '\\1') | first }}"
Output
ok: [prod_server] => {
"dbuser": "', 'username' );"
}
I would need to extract only the username
part and get rid of all other characters.
I tried to play a bit with regular expressions, and I managed to build up one that apparently extracts the username
part putting it into Group 1: https://regex101.com/r/OzJR1X/2
If I try to add it to my code, an error shows up:
Syntax Error while loading YAML.
found unknown escape character 's'
Create a dictionary of the parameters. Given the list of the lines, e.g.
- set_fact:
wpconfig_list: "{{ lookup('file', 'wpconfig.conf').splitlines() }}"
wpconfig_list:
- define( 'DB_USER', 'username' );
- define( 'DB_PASSWORD', 'password' );
Fit the code to your needs potentially using wpconfig.stdout_lines
The task creates the dictionary
- set_fact:
wpconfig_dict: "{{ wpconfig_dict|default({})|
combine({_key: _val}) }}"
loop: "{{ wpconfig_list }}"
vars:
_regex1: '^.*\((.*),(.*)\).*$'
_regex2: "'"
_key: "{{ item|regex_replace(_regex1, '\\1')|trim|
regex_replace(_regex2, '') }}"
_val: "{{ item|regex_replace(_regex1, '\\2')|trim|
regex_replace(_regex2, '') }}"
wpconfig_dict:
DB_PASSWORD: password
DB_USER: username
Select the user, e.g.
- set_fact:
dbuser: "{{ wpconfig_dict.DB_USER }}"
gives
dbuser: username