在Jinja2语句中使用Jinja2表达式

时间:2018-05-17 01:04:47

标签: ansible jinja2

我们说我有以下Jinja2变量:

  • ' dev_ami' =' ami-123456'
  • ' dev_located_ami' =' ami-123456'
  • ' prod_ami' =' ami-654321'
  • ' prod_located_ami' =' ami-654321'

我想设定一个条件,当'dev_ami'变量等于' dev_located_ami'变量。这很容易完成,如下面的陈述所示:

{% if dev_ami == dev_located_ami %}
... do some stuff
{% else %}
... do some other stuff
{% endif %}

但我想根据列表中包含的部署环境动态比较amis [' dev',' prod'等等...]。以下包含模板错误,因为在语句中有一个表达式 - {% {{ .. }} %}

{% for env_type in ['dev','prod'] %}
{% if {{ env_type }}_ami == {{ env_type }}_located_ami %}
... do stuff
{% else %}
... do other stuff
{% endif %}
{% endfor %}

我试图在下面的代码中设置变量来表示我想要的表达式,但不幸的是它们被编译为' dev_ami'和' dev_located_ami'而我希望他们编译成相应的变量值' ami-123456'和' ami-123456':

{% for env_type in ['dev','prod'] %}
{% set ami = "%s_ami"|format(env_type) %}
{% set located_ami = "%s_located_ami"|format(env_type) %}
{% if ami == located_ami %}
... do stuff
{% else %}
... do other stuff
{% endif %}
{% endfor %}

我已经检查了各种过滤器,到目前为止没有成功。希望获得有关使此特定实现正常工作的建议。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我认为您可能正在考虑错误的数据结构问题。

动态生成变量名称以便在不同的环境中比较amis听起来像是对我来说是一个巨大的矫枉过正。你熟悉名单和吗?词典?

尝试从这样的事情开始(伪代码):

     // 1.0 to test signal of extQObject10 which is moved to extQThread1
     // and signal of extQObject11 which is not moved
+    QTimer timer;
+    timer.setSingleShot(true);
     long timeout = 5000;
-    QTimer::singleShot(timeout, [&extQThread1, &timeout]() {
+    QObject::connect(&timer, &QTimer::timeout, [&extQThread1, &timeout]() {
         qDebug() << "\n==" << QDateTime::currentMSecsSinceEpoch() - baseMSecsSinceEpoch << "timeout" << timeout
                  << "\n>> To test signal of extQObject10 which is moved to extQThread1 and signal of extQObject11 which is not moved"
                  << "\n>> extQThread1.isRunning()" << extQThread1.isRunning();
     });
-    QTimer::singleShot(timeout, &extQObject10, &ExtentQObject::onExtentQObjectFirstSlot);
-    QTimer::singleShot(timeout, &extQObject11, &ExtentQObject::onExtentQObjectFirstSlot);
+    QObject::connect(&timer, &QTimer::timeout, &extQObject10, &ExtentQObject::onExtentQObjectFirstSlot);
+    QObject::connect(&timer, &QTimer::timeout, &extQObject11, &ExtentQObject::onExtentQObjectFirstSlot);
+    timer.start(timeout);