I want to extract a few regex matches out of a URL. The only way I could do this was following:
- name: Set regex pattern for github URL
set_fact: pattern="^(git\@github\.com\:|https?\:\/\/github.com\/)(.*)\/([^\.]+)(\.git)?$"
- name: Extract organization name
set_fact: project_repo="{{ deploy_fork | regex_replace( "^(git\@github\.com\:|https?\:\/\/github.com\/)(.*)\/([^\.]+)(\.git)?$", "\\3" ) }}"
when: deploy_fork | match( "{{ pattern }}" )
With this approach, I'm able to reuse the variable pattern
in the match
filter, but not on the set_fact
line where I assign the extracted text to another variable.
Is there any way to reuse the variable in set_fact
that uses filter(s)
?
To solve this problem, Ansible offers us one module named “include_vars” which loads variables from files dynamically within the task. This module can load the YAML or JSON variables dynamically from a file or directory, recursively during task runtime.
Ansible uses the jinja2 template. the {{ }} are used to evaluate the expression inside them from the context passed. So {{ '{{' }} evaluates to the string {{ And the while expression {{ docroot }} is written to a template, where docroot could be another template variable.
Variable Setting Options & Precedence As we have previously seen, the most straightforward way is to define variables in a play with the vars section. Another option is to define variables in the inventory file. We can set variables per host or set shared variables for groups.
The easiest way to pass Pass Variables value to Ansible Playbook in the command line is using the extra variables parameter of the “ansible-playbook” command. This is very useful to combine your Ansible Playbook with some pre-existent automation or script.
You should just be able to reference the defined variables directly. Try this; it worked for me:
- name: Set regex pattern for github URL
set_fact: pattern="^(git\@github\.com\:|https?\:\/\/github.com\/)(.*)\/([^\.]+)(\.git)?$"
- name: Extract organization name
set_fact: project_repo="{{ deploy_fork | regex_replace(pattern, "\\3" ) }}"
when: deploy_fork | match(pattern)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With