Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ansible, how to use a variable inside a variable definition that uses filters

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) ?

like image 564
Nikhil Owalekar Avatar asked Oct 13 '15 20:10

Nikhil Owalekar


People also ask

How do I use dynamic variables in Ansible?

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.

What does {{ }} mean in Ansible?

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.

How do you define multiple variables in Ansible?

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.

How do you pass variables in Ansible script?

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.


1 Answers

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)
like image 173
Dan Avatar answered Sep 19 '22 06:09

Dan