Ansible - 当数组已经有变量时,无法向数组中的每个项目添加前缀 'ansible_hostname'

Ansible - Not able to add prefix 'ansible_hostname' to each item in an array when array already has variables

我正在尝试将 'ansible_hostname' 作为前缀添加到数组中的每个项目,但得到了两个不同的结果。

我用变量声明了数组,在不使用循环的情况下传递主机名时需要帮助。

场景 1:

  - name: test_array
    set_fact:
     test_array: ["This is test1 {{ansible_hostname}}", "This is test2"]     
  - set_fact: 
      test_fact: "{{ test_array | map('regex_replace', '^(.*)$', ' {{ansible_hostname}}, \1') | join('\n') }}" 

output:
"test_fact": " {{ansible_hostname}}, This is test1 control\n {{ansible_hostname}}, This is test2"

场景 2:

 - name: test_array
    set_fact:
     test_array: ["This is test1", "This is test2"]    
  - set_fact: 
      test_fact: "{{ test_array | map('regex_replace', '^(.*)$', ' {{ansible_hostname}}, \1') | join('\n') }}" 

output:
"test_fact": " host, This is test1 control\n host, This is test2"

您不能在 jinja2 扩展中使用 jinja2 扩展。您必须使用 + 运算符将主机名与其​​余的正则表达式替换连接起来:

- set_fact: 
    test_fact: "{{ test_array | map('regex_replace', '^(.*)$', ansible_hostname + ', \1') | join('\n') }}"