【问题标题】:In ansible how do I concatenate a already defined variable in a settings file yaml and an extra-var?在 ansible 中,我如何在设置文件 yaml 和 extra-var 中连接一个已经定义的变量?
【发布时间】:2023-01-26 00:00:19
【问题描述】:

我创建了一个名为 settings.yaml 的设置文件,如下所示:

cust_int: 'ens224'
cust_sub_int: '{{ cust_int }}.{{ cust }}
  • cust_int,就是上面已经定义好的变量
  • cust,是--extra-var提供的变量

这是剧本:

- name: Include vars
  include_vars:
      file: ../../../settings.yaml
      name: settings

- debug: msg="{{ settings.cust_sub_int }}"

当尝试以这种方式连接时,我得到不清楚的错误,即剧本“没有找到预期的密钥”。

我的问题是,如何在我的设置文件中组合这两个变量?我不想在我所有的剧本中都使用set_fact

【问题讨论】:

标签: variables ansible yaml concatenation


【解决方案1】:

请参阅ansible cannot use variable 了解这不起作用的详细信息。解决方案相当简单。将设置拆分为公共变量和字典。例如,

shell> cat settings-common.yaml
_cust_int: 'ens224'
shell> cat settings.yaml
cust_int: '{{ _cust_int }}'
cust_sub_int: '{{ _cust_int }}.{{ cust }}'

包括这两个文件

    - include_vars:
        file: settings-common.yaml
    - include_vars:
        file: settings.yaml
        name: settings

使用额外的变量运行游戏cust=foo给出了预期的结果

  settings:
    cust_int: ens224
    cust_sub_int: ens224.foo

完整的测试项目示例

shell> tree .
.
├── ansible.cfg
├── hosts
├── pb.yml
├── settings-common.yaml
└── settings.yaml

0 directories, 5 files
shell> cat ansible.cfg 
[defaults]
gathering = explicit
inventory = $PWD/hosts
retry_files_enabled = false
stdout_callback = yaml
shell> cat hosts 
localhost
shell> cat pb.yml 
- hosts: localhost

  tasks:

    - include_vars:
        file: settings-common.yaml
    - include_vars:
        file: settings.yaml
        name: settings

    - debug:
        var: settings
    - debug:
        msg: "{{ settings.cust_sub_int }}"

shell> ansible-playbook pb.yml -e cust=foo

PLAY [localhost] *****************************************************************************************************************

TASK [include_vars] **************************************************************************************************************
ok: [localhost]

TASK [include_vars] **************************************************************************************************************
ok: [localhost]

TASK [debug] *********************************************************************************************************************
ok: [localhost] => 
  settings:
    cust_int: ens224
    cust_sub_int: ens224.foo

TASK [debug] *********************************************************************************************************************
ok: [localhost] => 
  msg: ens224.foo

PLAY RECAP ***********************************************************************************************************************
localhost: ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 2020-09-15
    • 2019-04-19
    • 2014-07-28
    • 2017-09-08
    • 2020-07-07
    相关资源
    最近更新 更多