大网数据广告活动
服务器运维问答

Ansible: Conditionally define variables in vars file if a certain condition is met

· 52CE 我爱测

Depending on the value(True/False) of a variable defined into the group_vars I am trying to define some variables in a vars file. Their value depends on the group var's value. My current var file looks like this: {% if my_group_v…

问题原文

原帖链接 · pandoJohn · CC BY-SA 3.0

Depending on the value(True/False) of a variable defined into the group_vars I am trying to define some variables in a vars file. Their value depends on the group var's value.

My current var file looks like this:

{% if my_group_var %}
test:
   var1: value
   var2: value
   ...
   varn: value
{% else %}
test:
   var1: other_value
   var2: other_value
   ...
   varn: other_value
{% endif %}

For each one of my roles I'm using a variable defined into this file.

My test playbook looks like below:

- name: blabla
  hosts: blabla
  vars_files:
     - <path>/test_vars.yml
  roles: blabla 

The error I'm receiving after running the playbook is:

{% if my_group_var %}
 ^ here

exception type: <class 'yaml.scanner.ScannerError'>
exception: while scanning for the next token
found character that cannot start any token
  in "<unicode string>"

Am I doing something stupid here or this is not even supported? I've tried to find another way for defining these vars(I have a lot of them) but I didn't managed to get something functional here. Any suggestions?

已采纳解答

原帖链接 · pandoJohn · CC BY-SA 4.0

What I did in the end was to create 2 separate var files - let's call them type_a.yml and type_b.yml - and I defined a group variable that indicates what file to use - something like type_of_file: a. This is how my playbook looks now:

- name: blabla
  hosts: blabla
  vars_files:
     - <path>/type_{{ type_of_file }}.yml
  roles: blabla

Thanks for all the answers. I find them really helpful.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-04-11)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。