【问题标题】:Ansible - Compare a variable (string) against the dict/list (of strings) and find the match with the highest number and extract that numberAnsible - 将变量(字符串)与(字符串的)字典/列表进行比较,并找到具有最高数字的匹配项并提取该数字
【发布时间】:2022-08-02 15:47:57
【问题描述】:

我编写了一个创建新资源或多个资源的剧本。该资源的名称是通过各种用户输入生成的,并带有一个加法 - 一个数字。因此,生成的名称看起来像 resource_name_1、resource_name_2,具体取决于创建了多少资源。如果不存在具有相同名称的现有资源(用户输入和数字的组合),那效果很好。

因此,我需要检查是否已经部署了具有相同名称的资源,换句话说,将这个新生成的名称与收集的名称列表进行比较。

如果没有匹配,则以“普通”方式创建它。 如果匹配,则找到具有最高编号的匹配名称(因为可能已经有 20 个资源),提取并增加这个最高编号 (20),并将其用作新的资源名称。

我可以像这样收集现有资源名称的列表:

resources_names_list: \"{{ resource_name_info.resource | map(attribute=\'name\') }}\"

示例列表如下所示:

ok: [localhost] => {
    \"msg\": [
        \"resource-1\",
        \"ex1\",
        \"someresource2\",
        \"ppp-1\",
        \"pd5\",
        \"sample65kk \",
        \"prod5\",
        \"sample\",
        \"stars3232demo\",
    ]
}

这是循环:

 - debug: msg: match is found \"{{item2}}\" 
   when: (my_generated_resource_name in item2) 
   loop: \"{{resources_names_list}}\" 
   loop_control: 
     loop_var: item2

此循环确实将生成资源名称与列表中收集的名称进行比较。所以现在它应该适应找到匹配项,但具有最高的数字。应该提取最高的数字,递增,然后用于生成新的资源名称。

谢谢!

    标签: list ansible duplicates compare highest


    【解决方案1】:

    我让其他任务(最大和增量)像这样工作:

        - name: Find maximum number from the list list2
          set_fact:  
            max_number: "{{ list2 | map('int') | max }}"
    
        - debug:
            msg: "{{ max_number }}"
    
        - name: increment number
          set_fact:
            number: "{{max_number|int + 1}}"
    
        - debug:
            msg: incremented number is "{{ number }}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      相关资源
      最近更新 更多