在 Ansible 中,如何在使用过滤器的变量定义中使用变量

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

我想从 URL 中提取一些正则表达式匹配项。我能做到这一点的唯一方法如下:

  - 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 }}" )

通过这种方法,我可以在 match 过滤器中重用变量 pattern,但不能在 set_fact 行上重用,我将提取的文本分配给另一个变量. 有什么方法可以重用 set_fact 中使用 filter(s) 的变量?

您应该能够直接引用定义的变量。试试这个;它对我有用:

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

You don’t need to use {{ }} to use variables inside conditionals, as these are already implied.

您可以在此处找到详细说明Ansible Conditionals