使用变量作为字典键时,变量扩展在Ansible Playbook中不起作用

时间:2016-10-04 11:06:00

标签: ansible

我用以下变量执行了ansible-playbook命令。

命令

ansible-playbook -vvv reconfig_vm.yml --extra-vars '{"disks":[{"name":"disk1","size_gb":"30","type":"thin","datastore":"nfs01"},{"name":"disk2","size_gb":"15","type":"thin","datastore":"nfs01"}}'  

然后,创建以下Playbook。

Playbook Content(reconfig_vm.yml)

..(omitted)..
tasks:
- name: reconfig VM Disk
    local_action:
      module: vsphere_guest

           ..(omitted)..

      vm_disk:
        "{{ item.name }}":
          size_gb: "{{ item.size_gb }}"
          type: "{{ item.type }}"
          datastore: "{{ item.datastore }}"

                  ..(omitted)..

  with_items: "{{ disks }}"

当我运行这个剧本时,我得到了以下结果。

执行结果

failed: [localhost -> localhost] (item={u'size_gb': u'30', u'type':     u'thin', u'name': u'disk1', u'datastore': u'nfs01'}) => {"failed": true, "invocation": {"module_name": "vsphere_guest"}, "item": {"datastore": "nfs01", "name": "disk1", "size_gb": "30", "type": "thin"}, "module_stderr": "Traceback (most recent call last):\n  File   *..(omitted)..* ansible_module_vsphere_guest.py\", line 793, in update_disks\n    hd.UnitNumber = int(disk_id)\nValueError: invalid literal for int() with base 10: '{{ item.name }}'\n", "module_stdout": "", "msg": "MODULE FAILURE", "parsed": false}  

问题

执行结果表明" {{item.name}}"在Playbook中没有替换为我给出的变量--extra-vars。

  1. 您是否有任何想法扩展--extra-vars作为字典键?

  2. 您有什么其他想法可以解决这个问题吗?

  3. 提前谢谢你。

    运行良好的代码(已解决

    感谢Konstantin Suvorov的回答,我终于创建了一个代码,可以完成我想做的工作。

    @Playbook Content(reconfig_vm.yml)

    tasks:
    - set_fact:
        vm_disk_solo: "'{{ item.name }}':{'size_gb':'{{ item.size_gb }}','type':'{{ item.type }}','datastore':'{{ item.datastore }}'}"  
      with_items: "{{ vm.disks }}"  
      register: vm_disk_mul  
    
    - set_fact:  
        vm_disks: "{ {{ vm_disk_mul.results | join(',',attribute='ansible_facts.vm_disk_solo') }} }"  
    
    
    - name: reconfig VM Disk  
      local_action:  
        module: vsphere_guest  
    
        ..(omitted)..  
    
        vm_disk: "{{ vm_disks }}"  
    

1 个答案:

答案 0 :(得分:1)

最简单的方法是以适当的格式传递extra-var:

--extra-vars '{"disks":{"disk1":{"size_gb":"30","type":"thin","datastore":"nfs01"},"disk2":{"size_gb":"15","type":"thin","datastore":"nfs01"}}}'

并且无需循环即可传递vm_disk: "{{ disks }}"

如果您仍需要遍历列表,则需要在调用vsphere_guest之前设置一些动态事实。见https://stackoverflow.com/a/37731028/2795592