【问题标题】:Looking to see if a key from one set of imported variables matches another so it's value can be procured查看一组导入变量中的一个键是否与另一个匹配,以便可以获取它的值
【发布时间】:2022-08-18 15:56:50
【问题描述】:

我已经粗略地格式化了 yml 文件,其中包含键/值对。然后,我使用include_vars 模块将这两个文件的值成功导入到正在运行的剧本中。

现在,我希望能够将文件/列表 1 中的键/值对的值与文件/列表 2 的所有键进行比较。最后,当匹配时,打印并最好保存/注册该值来自文件/列表 2 的匹配键。

本质上,我将机器名称与 IP 列表进行比较,以尝试从该列表中获取机器所需的 IP。名称是 \"dynamic\" 并且每次运行 playbook 时都会有所不同,因为文件/列表 1 总是在每次运行时动态填充。

例子:

文件/列表 1 内容

machine_serial: m60
s_iteration: a
site_name: dud
t_number: \'001\'

文件/列表 2 内容

m51: 10.2.5.201
m52: 10.2.5.202
m53: 10.2.5.203
m54: 10.2.5.204
m55: 10.2.5.205
m56: 10.2.5.206
m57: 10.2.5.207
m58: 10.2.5.208
m59: 10.2.5.209
m60: 10.2.5.210
m61: 10.2.5.211

简而言之,我希望能够获取文件/列表 1 ct_machine_serial key who\'s value current is: m60 以便能够在文件/列表 2 中找到它的密钥匹配,然后打印和/或最好注册它的值 10.2.5.210。

到目前为止我已经尝试过: 剧本:

 - name: IP gleaning comparison.  
   hosts: localhost
   remote_user: ansible
   become: yes
   become_method: sudo
   vars:
     ansible_ssh_pipelining: yes

   tasks:

     - name: Try to do a variable import of the file1 file.
       include_vars:
         file: ~/active_ct-scanner-vars.yml
         name: ctfile1_vars
       become: no

     - name: Try to do an import of file2 file for lookup comparison to get an IP match.
       include_vars:
         file: ~/machine-ip-conversion.yml
         name: ip_vars
       become: no

     - name: Best, but failing attempt to get the value of the match-up IP.  
       debug:
         msg: \"{{ item }}\"
       when: ctfile1_vars.machine_serial == ip_vars
       with_items:
         - \"{{ ip_vars }}\"

除最后一项外,每项任务都完美无缺。
我失败的输出最终任务:

TASK [Best, but failing attempt to get the value of the match-up IP.] ***********************************************************************************
skipping: [localhost] => (item={\'m51\': \'10.200.5.201\', \'m52\': \'10.200.5.202\', \'m53\': \'10.200.5.203\', \'m54\': \'10.200.5.204\', \'m55\': \'10.200.5.205\', \'m56\': \'10.200.5.206\', \'m57\': \'10.200.5.207\', \'m58\': \'10.200.5.208\', \'m59\': \'10.200.5.209\', \'m60\': \'10.200.5.210\', \'m61\': \'10.200.5.211\'})
skipping: [localhost]

我希望的事情没有发生,它只是跳过了任务,并且没有像我希望的那样遍历列表,所以一定是某个地方出现了问题。希望有一个我刚刚错过的简单解决方案。什么可能是正确的答案?

    标签: list ansible yaml


    【解决方案1】:

    简短回答:变量ip_vars是一本字典。利用ctfile1_vars.machine_serial作为索引

    match_up_IP: "{{ ip_vars[ctfile1_vars.machine_serial] }}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-08
      • 2018-06-06
      • 2022-01-08
      相关资源
      最近更新 更多