首页 > 解决方案 > Ansible - 当数组已经有变量时,无法为数组中的每个项目添加前缀“ansible_hostname”

问题描述

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

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

场景一:

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

场景二:

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

标签: ansibleansible-facts

解决方案


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

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


推荐阅读