【问题标题】:How to access an ansible block variable in a file from the same block如何从同一块访问文件中的 ansible 块变量
【发布时间】:2019-10-28 01:34:33
【问题描述】:

我为 ansible 定义了一个 yml 变量文件,结构如下:

appserver:
   root_directory: C:\app
   config_directory: '{{ root_directory }}\config'

似乎无法正确解释第二个变量config_directory,我得到了VARIABLE NOT FOUND ERROR

我试过了:

appserver:
   root_directory: C:\app
   config_directory: '{{ appserver.root_directory }}\config'

它也不起作用,我有很长的错误痕迹,最有趣的部分是:

recursive loop detected in template string:{{ appserver.root_directory }}\config

当我使用双引号而不是单引号时,

应用服务器: 根目录:C:\app config_directory: "{{ appserver.root_directory }}\config"

我收到以下错误:

 The offending line appears to be:

 app_root: D:\WynsureEnvironments\Application
 wynsure_root: "{{ appserver.root_directory }}\config"
                                              ^ here
 We could be wrong, but this one looks like it might be an issue with
 missing quotes.  Always quote template expression brackets when they
 start a value. For instance:

with_items:
  - {{ foo }}

应该写成:

with_items:
  - "{{ foo }}"

在使用变量块时,如何重复使用变量来分配新变量?

谢谢!

【问题讨论】:

    标签: ansible yaml ansible-2.x


    【解决方案1】:

    你不能在 ansible 中使用这样的递归 jinja2 变量声明。

    这里有 2 个(非详尽列表)替代解决方案:

    1. 不要使用哈希。预先添加您的变量名称。您通常会在例如找到这种类型的命名约定。 ansible galaxy 上的可重用角色
    appserver_root_directory: C:\app
    appserver_config_directory: '{{ appserver_root_directory }}\config'
    
    1. 如果您确实需要这种散列,请在散列外部声明一个“私有”变量并在内部重用它。
    _appserver_root: C:\app
    appserver:
      root_directory: "{{ _appserver_root }}"
      config_directory: "{{ _appserver_root }}\config"
    

    【讨论】:

    • 错误出现在我在 stackoverflow 上的帖子中,我确实加了引号(虽然是简单的引号),但它不起作用。我会尝试使用双引号。
    • 使用简单的引号,我得到一个错误,比如“检测到递归循环”。
    • it does not work, It does not even parse with double quotes => 请编辑您的帖子并向我们显示错误。也请花时间阅读"how do I create a minimal reproducible example"
    • 对不起,我第一次阅读时忽略了您的内容。您不能在 jinja2 中使用这种类型的递归声明。用替代品更新我的答案。
    • 看来我不能在同一个块中使用一个块的变量,对吧?
    猜你喜欢
    • 2015-06-22
    • 2015-05-15
    • 1970-01-01
    • 2020-12-30
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多