本文介绍了Ansible:如何从另一个变量构造一个变量,然后获取它的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题,我需要使用一个变量target_host",然后将_host"附加到它的值以获得另一个我需要其值的变量名称.如果你看看我的剧本.任务 nbr 1,2,3 获取变量的值,但是 nbr 4 无法实现我的预期.有没有其他方法可以在ansible中实现相同的目标?

Here is my problem I need to use one variable 'target_host' and then append '_host' to it's value to get another variable name whose value I need.If you look at my playbook. Task nbr 1,2,3 fetch the value of variable however nbr 4 is not able to do what I expect. Is there any other way to achieve the same in ansible?

   ---
    - name: "Play to for dynamic groups"
      hosts: local
      vars:
        - target_host: smtp
        - smtp_host: smtp.max.com
      tasks:
        - name: testing
          debug: msg={{ target_host }}
        - name: testing
          debug: msg={{ smtp_host }}
        - name: testing
          debug: msg={{ target_host }}_host
        - name: testing
          debug: msg={{ {{ target_host }}_host }}


Output:

TASK: [testing] ***************************************************************
ok: [127.0.0.1] => {
    "msg": "smtp"
}

TASK: [testing] ***************************************************************
ok: [127.0.0.1] => {
    "msg": "smtp.max.com"
}

TASK: [testing] ***************************************************************
ok: [127.0.0.1] => {
    "msg": "smtp_host"
}

TASK: [testing] ***************************************************************
ok: [127.0.0.1] => {
    "msg": "{{{{target_host}}_host}}"
}

推荐答案

你需要在它周围加上引号:

You need to put quotes around it:

- hosts: local
  vars: [ target_host: smtp ]
  tasks:
    debug: msg="{{ target_host }}_host"

-- 编辑 --

Kashyap 我需要比这多上一层.想象有另一个变量smtp_host",我想在运行时使用另一个变量(target_host)并附加一个字符串'_host' 到它.= {{ {{ target_host }}_host }} – 最大

我的错.阅读不够仔细.

My bad. Didn't read carefully enough.

这(AFAIK)是不可能的.阻止我们这样做的主要限制(无论您如何旋转),是 ansible 中的变量扩展"是单遍过程,而您想要的需要多次传递.

This (AFAIK) isn't possible. The primary limitation that stops us doing this (no matter how you spin it), is 'variable expansion' in ansible is a single pass process and what you want requires multiple-passes.

我能想到的唯一[严重hacky]方法是:

Only [seriously hacky] ways I can think of are:

  • 使用template从你的剧本动态创建剧本并执行它.
  • 听说 Jinja2 引擎会进行多次评估.可能是如果您将这些字符串放在模板中,然后使用 lookup('template', ...) 过滤器.不幸的是,我没有使用 Jinja2 模板的经验,所以不太确定这是否是一种选择.
  • Create the playbook dynamically from your playbook using template and execute it.
  • I heard that Jinja2 engine does multi-pass evaluation. May be if you put these strings in a template and then use the lookup('template', ...) filter. Unfortunately I have no experience with Jinja2 templates so not quite sure if this is even an option.

这篇关于Ansible:如何从另一个变量构造一个变量,然后获取它的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:02
查看更多