resolve dictionary key or parameter variable in Ansible

前端 未结 2 839
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 07:34

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:



        
相关标签:
2条回答
  • 2020-12-05 08:14

    Another option - you can try something like:

      module_name: "{{ item.key }}={{ item.value }}"
      with_items:
      - { key: "option", value: "{{ any_value }}" }
    

    Please note that everything is inline and I'm using an equal (=) and everything is wrapped with double quotes.

    0 讨论(0)
  • 2020-12-05 08:37

    Will this work for you?

    (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)$
    

    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.

    0 讨论(0)
提交回复
热议问题