AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-5473898

zagpoint's questions

Martin Hope
zagpoint
Asked: 2025-04-09 03:07:32 +0800 CST

如何按列表成员的属性进行版本排序

  • 8

我正在尝试按照以下代码示例中的“名称”字段正确排序列表:

---
  - hosts: localhost
    vars:
      hosts:
        - name: host2
          uptime: 1d
        - name: host10
          uptime: 45d
        - name: host1
          uptime: 3m

    tasks:
    - name: version sort host list
      debug:
        #var: hosts | community.general.version_sort
        #var: hosts | dictsort(false, 'value')
        var: hosts | sort(attribute='name')

如您所见,它没有正确排序主机名(host2 应该排在 host10 之前)。我查了一下 version_sort 过滤器,但它不支持按属性排序。我知道如果主机名正确填充,就不会出现这种情况。但事实就是如此。我搜索了一下,没有看到有人问这个问题。还有其他建议吗?

TASK [version sort host list] *************************************
ok: [localhost] => {
    "hosts | sort(attribute='name')": [
        {
            "name": "host1",
            "uptime": "3m"
        },
        {
            "name": "host10",  <-------
            "uptime": "45d"
        },
        {
            "name": "host2",
            "uptime": "1d"
        }
    ]
}

概括:

感谢@Vladimir Botka提供的所有选项!我整合了第三个选项,并制定了以下方案。注意,我更新了字典列表,使其在使用fqdn时稍微复杂一些。但这个方案确实有效:

- hosts: localhost

  vars:
    hosts:
      - {name: host2.example.com, uptime: 1d}
      - {name: host10.example.com, uptime: 45d}
      - {name: host1.example.com, uptime: 3m}
      - {name: host3.example.com, uptime: 3m}
      - {name: host15.example.com, uptime: 45d}
      - {name: host20.example.com, uptime: 45d}
  tasks:
#    - debug:
#        msg: 
#        - "index: {{ hosts | map(attribute='name') | community.general.version_sort }}"
#        - "host_indexed: {{ dict(hosts|json_query('[].[name,@]')) }}"
#        - "solution: {{ (hosts | map(attribute='name') | community.general.version_sort) | map('extract', dict(hosts|json_query('[].[name,@]'))) }}"
    - debug: 
        var: (hosts | map(attribute='name') | community.general.version_sort) | map('extract', dict(hosts|json_query('[].[name,@]'))) 

结果如下:

PLAY [localhost] *****************************************************************************************************************************************
    
TASK [Gathering Facts] ***********************************************************************************************************************************
ok: [localhost]
    
TASK [debug] *********************************************************************************************************************************************
[WARNING]: Collection community.general does not support Ansible version 2.14.17
ok: [localhost] => {
    "(hosts | map(attribute='name') | community.general.version_sort) | map('extract', dict(hosts|json_query('[].[name,@]')))": [
        {
            "name": "host1.example.com",
            "uptime": "3m"
        },
        {
            "name": "host2.example.com",
            "uptime": "1d"
        },
        {
            "name": "host3.example.com",
            "uptime": "3m"
        },
        {
            "name": "host10.example.com",
            "uptime": "45d"
        },
        {
            "name": "host15.example.com",
            "uptime": "45d"
        },
        {
            "name": "host20.example.com",
            "uptime": "45d"
        }
    ]
}
    
PLAY RECAP ***********************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
ansible
  • 1 个回答
  • 50 Views
Martin Hope
zagpoint
Asked: 2025-04-05 07:25:48 +0800 CST

您可以动态更新 ansible 字典吗?

  • 7

我从 REST API 调用的输出中捕获了一个 dict/json 类型的对象,假设它位于一个名为ouput的变量/寄存器中。数据如下所示。为了完整起见,我分享了整个对象并做了一些基本的清理。请只关注我接下来要讨论的那一行 ;-)

            {
            "_create_time": 1724823837185,
            "_create_user": "system",
            "_last_modified_time": 1736218001919,
            "_last_modified_user": "nsx_policy",
            "_protection": "NOT_PROTECTED",
            "_revision": 1,
            "_system_owned": false,
            "display_name": "w1-vc1-c4n17.example.com",
            "host_switch_spec": {
                "host_switches": [
                    {
                        "cpu_config": [],
                        "ecmp_mode": "L3",
                        "host_switch_id": "50 01 cb 21 be 19 cb 38-78 bd 67 bc b3 0e 91 f1",
                        "host_switch_mode": "STANDARD",
                        "host_switch_name": "w1-vc1-c4-dvs",
                        "host_switch_profile_ids": [
                            {
                                "key": "UplinkHostSwitchProfile",
                                "value": "/infra/host-switch-profiles/6d7a0ed8-c86a-4190-9121-ce6f863226ae"
                            },
                            {
                                "key": "VtepHAHostSwitchProfile",
                                "value": "/infra/host-switch-profiles/0de8282e-7385-4e8e-a905-0c11960db728"
                            }
                        ],
                        "host_switch_type": "VDS",
                        "ip_assignment_spec": {
                            "ip_pool_id": "/infra/ip-pools/w1-nsx1-esxi-teps",
                            "resource_type": "StaticIpPoolSpec"
                        },
                        "is_migrate_pnics": false,
                        "not_ready": false,
                        "portgroup_transport_zone_id": "/infra/sites/default/enforcement-points/default/transport-zones/77166711-1f83-407f-8c27-a4e1b8b4e1e5",
                        "transport_zone_endpoints": [
                            {
                                "transport_zone_id": "/infra/sites/default/enforcement-points/default/transport-zones/4b367ddf-d4ac-460b-a884-24846ff4edf6",
                                "transport_zone_profile_ids": [
                                    {
                                        "profile_id": "/infra/transport-zone-profiles/52035bb3-ab02-4a08-9884-18631312e50a",
                                        "resource_type": "BfdHealthMonitoringProfile"
                                    }
                                ]
                            },
                            {
                                "transport_zone_id": "/infra/sites/default/enforcement-points/default/transport-zones/bc19b340-f0b5-46d8-9454-6d94d3288821",
                                "transport_zone_profile_ids": [
                                    {
                                        "profile_id": "/infra/transport-zone-profiles/52035bb3-ab02-4a08-9884-18631312e50a",
                                        "resource_type": "BfdHealthMonitoringProfile"
                                    }
                                ]
                            }
                        ],
                        "uplinks": [
                            {
                                "uplink_name": "uplink-2",
                                "vds_uplink_name": "uplink2"
                            },
                            {
                                "uplink_name": "uplink-1",
                                "vds_uplink_name": "uplink1"
                            }
                        ]
                    }
                ],
                "resource_type": "StandardHostSwitchSpec"
            },
            "id": "w1-vc1-c4n17-6adb838f-669c-48ca-b76f-e1238984ef93host-2171",
            "is_overridden": false,
            "maintenance_mode": "DISABLED",
            "marked_for_delete": false,
            "node_deployment_info": {
                "compute_collection_id": "6adb838f-669c-48ca-b76f-e1238984ef93:domain-c2147",
                "discovered_ip_addresses": [
                    "x.x.x.x",
                    "x.x.x.x"
                ],
                "discovered_node_id": "6adb838f-669c-48ca-b76f-e1238984ef93:host-2171",
                "fqdn": "w1-vc1-c4n17.example.com",
                "ip_addresses": [
                    "10.x.x.x"
                ],
                "managed_by_server": "10.x.x.x",
                "os_type": "ESXI",
                "os_version": "x.x.x"
            },
            "overridden": false,
            "owner_id": "1ae23909-d587-4683-a515-4c2001940803",
            "parent_path": "/infra/sites/default/enforcement-points/default",
            "path": "/infra/sites/default/enforcement-points/default/host-transport-nodes/w1-vc1-c4n17-6adb838f-669c-48ca-b76f-e1238984ef93host-2171",
            "realization_id": "c2c69a21-698a-4586-869a-7c0b0a651601",
            "relative_path": "w1-vc1-c4n17-6adb838f-669c-48ca-b76f-e1238984ef93host-2171",
            "remote_path": "",
            "resource_type": "HostTransportNode",
            "unique_id": "c2c69a21-698a-4586-869a-7c0b0a651601"
        }

我想通过更改以下行来更新该对象:

"host_switch_mode": "STANDARD",

到:

"host_switch_mode": "LEGACY",

我会将结果 JSON 作为消息体传递给 POST API 调用。我尝试过 anislbe 的组合过滤器,但没有得到预期的结果。例如:

- Name: example post/put API call
  uri:
    url: "https://{{ nsx }}/policy/api/v1/infra/host-transport-node-profiles/{{ id }}"
        force_basic_auth: yes
        validate_certs: no
        headers:
          Accept: "application/json"
          Content-Type: "application/json"
        user: "{{ username }}"
        password: "{{ password }}"
        method: PUT
        body: "{{ ouput | combine( {'host_switch_spec': {'host_switches': [ {'host_switch_mode': "LEGACY"},],}, }, recursive=true) }}"
        status_code: "200"
        body_format: json

使用组合过滤器,我看到的是,整个 host_switch_spec 部分被替换(因此丢失了其他属性,如 host_switch_name、host_switch_id 等),而不是仅仅合并相关行,这不是我想要的:

            "host_switch_spec": {
            "host_switches": [
                {
                    "host_switch_mode": "STANDARD"
                }
            ],
            "resource_type": "StandardHostSwitchSpec"
        },

我做错了什么?我查看了组合过滤器的手册页,并尝试了所有list_merge选项,但都无济于事。


更新:

为了简单起见,我在上一篇文章中没有提到的一个复杂问题是,我有一个包含这些“输出”数据对象的列表,我需要像下面这样循环处理它们。假设这个列表在变量“tn”中:

  # Modify the transport node json data on the fly and feed it to the API as message body
  - debug: 
      msg: 
        - "{{ item }}"
        - "{{ item | combine( {'host_switch_spec': {'host_switches': [ {'host_switch_mode': mode}, ], }, },) }}"
    with_items: "{{ tn }}"
    loop_control:
      label: "{{ item.display_name }}"

概括:

感谢大家的帮助和指导。我还没有完成端到端测试,但以下是我根据 Vladimir Botka 提供的精彩示例得出的结论:

      # how to modify the transport node json data on the fly and feed it to the API as message body
  - name: Testing switch mode update on the fly
    debug: 
      msg:
        #- "hs: {{ (item.host_switch_spec.host_switches + [ hs_update ]) | combine }}"
        #- "update: {{ {'host_switch_spec': {'host_switches': [ (item.host_switch_spec.host_switches + [ hs_update ]) | combine ]}} }}"
        #- "result: {{ item | combine({'host_switch_spec': {'host_switches': [ (item.host_switch_spec.host_switches + [ hs_update ]) | combine ]}}) }}"
        - "{{ item | combine({'host_switch_spec': {'host_switches': [ (item.host_switch_spec.host_switches + [ hs_update ]) | combine ]}}) }}"
    loop: "{{ tn }}"
    loop_control:
      label: "{{ item.display_name }}"
      index_var: counter
    vars:
      hs_update:
        host_switch_mode: "LEGACY"

结果看起来很有希望(显示最后一个-#24,并且仅显示部分以避免混乱):

ok: [localhost] => (item=w11-vc1-c1n24.example.com) => {
"msg": [
    "24':' STANDARD",
    {
        "_create_time": 1743198123451,
        "_create_user": "system",
        "_last_modified_time": 1743445520238,
        "_last_modified_user": "system",
        "_protection": "NOT_PROTECTED",
        "_revision": 2,
        "_system_owned": false,
        "display_name": "w11-vc1-c1n24.example.com",
        "host_switch_spec": {
            "host_switches": [
                {
                    "cpu_config": [],
                    "ecmp_mode": "L3",
                    "host_switch_id": "50 1e 66 c9 c5 fb da b3-5e 1f 45 fc 2a 42 99 50",
                    "host_switch_mode": "LEGACY",
                    "host_switch_name": "w11-vc1-dvs",
                    "host_switch_profile_ids": [
                        {
                            "key": "UplinkHostSwitchProfile",
                            "value": "/infra/host-switch-profiles/ace9be64-9728-4340-968e-a62dae6a3d00"
                        },
                        {
                            "key": "VtepHAHostSwitchProfile",
                            "value": "/infra/host-switch-profiles/0de8282e-7385-4e8e-a905-0c11960db728"
                        }
                    ],
                    "host_switch_type": "VDS",
json
  • 1 个回答
  • 75 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve