问题
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)
?
回答1:
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)
回答2:
You don’t need to use {{ }} to use variables inside conditionals, as these are already implied.
You can find detailed descriptions here Ansible Conditionals
来源:https://stackoverflow.com/questions/33112403/in-ansible-how-to-use-a-variable-inside-a-variable-definition-that-uses-filters