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

喜你入骨 提交于 2019-12-22 04:16:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!