如何在ansible(yaml)词典中找到他的价值的关键词?

时间:2017-07-12 14:18:54

标签: dictionary filter ansible jinja2

我有这本词典:

MyClouds:
  Devwatt:
    ExternalNetwork: PublicRSC
    Flavors:
      - Flavor_1cpu_1gb: Devwatt_1cpu_1gb
      - Flavor_1cpu_2gb: Devwatt_1cpu_2gb
      - Flavor_1cpu_4gb: Devwatt_1cpu_4gb
  Fuga:
    ExternalNetwork: Internet
    Flavors:
      - Flavor_1cpu_1gb: Fuga_1cpu_1gb
      - Flavor_1cpu_2gb: Fuga_1cpu_2gb
      - Flavor_1cpu_4gb: Fuga_1cpu_4gb
      - Flavor_1cpu_8gb: Fuga_1cpu_8gb

我必须从一个Openstack云迁移到另一个,我的一个问题是找到各种口味之间的对应关系。

我想在“Devwatt”中找到哪个味道(键)的值为“Devwatt_1cpu_2gb”,并在“Fuga”中获取相同键的值后

我尝试了很多解决方案(with-dict,when,jija filters,json_query)但我找不到办法做到这一点。

拜托,请问你能帮帮我吗?

2 个答案:

答案 0 :(得分:0)

为什么不使用dict的简单映射,其中键是“Devwatt”的味道和值是“Fuga”的味道,如下所示:

---
- hosts: localhost
  vars:
    FlavorsMapping:
      Devwatt_1cpu_1gb: Fuga_1cpu_1gb
      Devwatt_1cpu_2gb: Fuga_1cpu_2gb
      Devwatt_1cpu_4gb: Fuga_1cpu_4gb
  tasks:
    - debug:
        var: FlavorsMapping['Devwatt_1cpu_2gb']

答案 1 :(得分:0)

受到Eric的回答和usefull resource的启发,我终于使用了这个解决方案:

我改变了一点我的数据结构并将其放在文件matrice.yml:

MyClouds:
  Devwatt:
    ExternalNetwork: PublicRSC
    Flavors:
      - name: Flavor_1cpu_1gb
        FlavorName: Devwatt_1cpu_1gb
      - name: Flavor_2cpu_1gb
        FlavorName: Devwatt_2cpu_1gb
      - name: Flavor_1cpu_2gb
        FlavorName: Devwatt_1cpu_2gb   

  Fuga:
    ExternalNetwork: Internet
    Flavors:
      - name: Flavor_1cpu_1gb
        FlavorName: Fuga_1cpu_1gb
      - name: Flavor_2cpu_1gb
        FlavorName: Fuga_2cpu_1gb
      - name: Flavor_1cpu_2gb
        FlavorName: Fuga_1cpu_2gb

然后我在我的剧本中使用了这些过滤器:

---
- hosts: localhost
  connection: local
  gather_facts: false

  vars:
    SourceFlavorName: "Devwatt_2cpu_1gb"

  tasks:
  - name: get flavors matrice
    include_vars:
      file: matrice.yml

  - name: Get generic name from flavor name of source cloud
    debug:
      msg: "{{ MyClouds.Devwatt.Flavors | selectattr('FlavorName','search','^'+ SourceFlavorName +'$') |map (attribute='name') | list }}"
    register: result

  - name: Get flavor name for target cloud from generic name
    debug:
      msg: "{{ MyClouds.Fuga.Flavors | selectattr('name','search','^'+ result.msg[0] +'$') |map (attribute='FlavorName') | list }}"

通过这个解决方案,我可以拥有任意数量的云,并且可以轻松找到从一个源云到目标云的风格之间的对应关系。