在 Ansible 中解析字典键或参数变量 [英] resolve dictionary key or parameter variable in Ansible

查看:26
本文介绍了在 Ansible 中解析字典键或参数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ansible 中,如果我尝试将变量用作参数名称或键名称,则永远无法解析.例如,如果我有 {{ some_var }}: true,或者:

In Ansible, if I try to use a variable as a parameter name, or a key name, it is never resolved. For example, if I have {{ some_var }}: true, or:

template: "{{ resolve_me_to_src }}": "some_src"

变量只会按字面意思使用,永远不会解析.我的具体用例是将它与 ec2 模块一起使用,其中我的一些标签名称存储为变量:

the variables will just be used literally and never resolve. My specific use case is using this with the ec2 module, where some of my tag names are stored as variables:

- name: Provision a set of instances
  ec2:
    group: "{{ aws_security_group }}"
    instance_type: "{{ aws_instance_type }}"
    image: "{{ aws_ami_id }}"
    region: "{{ aws_region }}"
    vpc_subnet_id: "{{ aws_vpc_subnet_id }}"
    key_name: "{{ aws_key_name }}"
    wait: true
    count: "{{ num_machines }}"
    instance_tags: { "{{ some_tag }}": "{{ some_value }}", "{{ other_tag }}": "{{ other_value }}" }

有什么办法可以解决这个问题吗?我可以标记我想以某种方式强制评估吗?

Is there any way around this? Can I mark that I want to force evaluation somehow?

推荐答案

这对你有用吗?

(rc=0)$ cat training.yml
- hosts: localhost
  tags: so5
  gather_facts: False
  vars: [
      k1: 'key1',
      k2: 'key2',
      d1: "{
        '{{k1}}': 'value1',
        '{{k2}}': 'value2',
      }",
    ]
  tasks:
  - debug: msg="{{item}}"
    with_dict: "{{d1}}"


(rc=0)$ ansible-playbook training.yml -t so5

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

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

TASK: [debug msg="{{item}}"] ************************************************** 
ok: [localhost] => (item={'key': 'key2', 'value': 'value2'}) => {
    "item": {
        "key": "key2", 
        "value": "value2"
    }, 
    "msg": "{'value': 'value2', 'key': 'key2'}"
}
ok: [localhost] => (item={'key': 'key1', 'value': 'value1'}) => {
    "item": {
        "key": "key1", 
        "value": "value1"
    }, 
    "msg": "{'value': 'value1', 'key': 'key1'}"
}

PLAY RECAP ******************************************************************** 
localhost                    : ok=1    changed=0    unreachable=0    failed=0   

(rc=0)$

技巧是用双引号包裹 dict 声明.Ansible 将这种未记录(但一致)和蹩脚的翻译(ansible 相当于 shell 变量扩展)应用于剧本中的大多数(不是全部)YAML 值(':' 的所有 RHS).这是将这些字符串以某种未知顺序通过 Jinja2-engine、Python-interpreter 和 ansible-engine 的某种组合.

Trick is to wrap dict declaration with double quotes. Ansible applies this undocumented (but consistant) and crappy translation (ansible's equivalent of shell variable expantion) to most (not all) YAML values (everything RHS of ':') in the playbook. It is some combination putting these strings through Jinja2-engine, Python-interpreter and ansible-engine in some unknown order.

这篇关于在 Ansible 中解析字典键或参数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆