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

查看:189
本文介绍了在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将此无证件(但一致)和cr脚的翻译(anable相当于shell变量expantion)应用于剧本中的大多数(不是全部)YAML值(':'的所有RHS).这是一些组合,以未知顺序将这些字符串通过Jinja2引擎,Python解释器和ansible引擎.

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天全站免登陆