2017-06-30 125 views
0

我花了大部分时间试图解决这个问题,迄今为止失败了。我正在构建一些手册以使Splunk中的功能自动化,并试图从清单组E.G.中转换主机列表。Ansible concat vars字符串

[search_head] 
1.2.3.4 
5.6.7.8 

(编辑)我的预期(期望)从该剧的调试输出结果应该是: https://1-2-3-4-ansible_nodename:8089, https://5.6.7.8-ansible_nodename:8089

,我试图通过对正在运行的主机上运行以下剧本完成此:

--- 
    - name: Build search head list to initialize the captain 
    hosts: search_head 
    remote_user: ansible 
    vars: 
     inventory_file: ./inventory-ec2-single-site 
     search_head_uri: "{{ lookup('template', './bootstrap-sh-deployer.j2') }}" 
pre_tasks: 
    - include_vars: 
     dir: 'group_vars' 
     extensions: 
     - yml 
     - yaml 
tasks: 
    - name: dump array 
    debug: 
     msg: "{{ search_head_uri }}"` 

随着模板bootstrap-sh-deployer.j2(编辑):

{%- set search_head_uri = [] %} 
{% for host in groups['search_head'] %} 
    {%- if search_head_uri.append("https://" + [host][ansible_nodename] + ":8089") %} 
{%- endif %} 
{%- if not loop.last %}, {% endif -%} 
{%- endfor %} 

(编辑)。然而,与当前播放的错误: "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: {{ lookup('template', './bootstrap-sh-deployer.j2') }}: 'list object' has no attribute u'ip-10-10-0-55'\n\nThe error appears to have been in '/Users/christophergarrett/dev/splunk-ansible/deploy_ec2_testing.yml': line 16, column 9, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - name: dump array\n ^here\n"

编辑: 帖子编辑,以反映尝试收集主机的事实。最初我曾发布过尝试从库存文件中获取主机的IP,这是我以前的工作。

回答

1

一旦你打开Jinja2表达式或语句,你应该使用Jinja2语法。您不能将它们嵌套(即,您不能在{% %}内使用{{ }})。

{%- if search_head_uri.append("https://" + host + ":8089") %} 
+0

太棒了,它停止了错误。现在我试图从'inventory'文件中的每个主机获取'ansible_nodename'。 (%) {% - set search_head_uri = [true] +“:8089”)%} {%endif - %} {% - if not loop.last%},{%endif - %} {% - endfor%}' – AlmostGosu

+0

错误: ' 1.2.3.4]:失败! => { “failed”:true, “msg”:“字段'args'有一个无效的值,其中包含一个未定义的变量,错误为:{{lookup('template','。 /bootstrap-sh-deployer.j2')}}:'list object'没有属性u'ip-1-2-3-4'\ n \ n错误似乎出现在'/ Users/christophergarrett/dev/splunk-ansible/deploy_ec2_testing.yml':第16行第9列,但可能在文件中的其他位置,具体取决于确切的语法问题。\ n \ n违规行显示为:\ n \ n任务:\ n - 名称:dump array \ n^here \ n“ }' – AlmostGosu

+0

如果您有其他问题,请发布其他问题。以前,想想为什么你把方括号中的“host”括起来。 – techraf

0

这个工作 - 结合的答案上述固定神社格式和使用hostvars才能到ansible_nodename

{%- set search_head_uri = [] %} 
{% for host in groups['search_head'] %} 
    {{ "https://" + hostvars[host]['ansible_nodename'] + ":8089" }} 
    {%- if not loop.last %}, {% endif -%} 
{%- endfor %}