You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在YAML中读取textData.txt动态键值对,生成带固定常量的动态用户列表配置

动态生成目标YAML的实现方案

核心逻辑

  • 逐行读取textData.txt内容,自动过滤空行
  • 每行按首个冒号拆分,避免用户名包含冒号导致解析错误,拆分后去除首尾空白得到userid和username
  • 对每组解析结果追加固定常量字段something: false,组装为用户子项
  • 套入固定的顶层结构(name: "User Names"),整体输出为合法YAML格式
  • 完全适配动态变化的键值对数量,无需修改代码或结构常量

通用实现示例(Python + PyYAML)

首先安装依赖:
pip install pyyaml

实现代码

import yaml
from pathlib import Path

# 解析textData.txt
user_items = []
for line in Path("textData.txt").read_text(encoding="utf-8").splitlines():
    stripped_line = line.strip()
    # 跳过空行
    if not stripped_line:
        continue
    # 仅按第一个冒号拆分,兼容用户名包含冒号的场景
    user_id, username = stripped_line.split(":", 1)
    # 组装用户项,内置固定常量
    user_items.append({
        "userid": user_id.strip(),
        "username": username.strip(),
        "something": False
    })

# 组装目标YAML结构
final_yaml = [
    {
        "name": "User Names",
        "users": user_items
    }
]

# 输出格式化YAML
print(yaml.dump(
    final_yaml,
    allow_unicode=True,
    default_style='"',
    sort_keys=False
))

输入输出测试

输入文件textData.txt(示例)

user1: john
user2: bob
user3: william

运行后输出的YAML(完全符合需求)

- name: "User Names"
  users:
  - userid: "user1"
    username: "john"
    something: false
  - userid: "user2"
    username: "bob"
    something: false
  - userid: "user3"
    username: "william"
    something: false

如果textData.txt新增任意行键值对(比如user4: alice),代码会自动追加对应的用户子项,无需修改任何逻辑。

Ansible 实现示例(YAML驱动场景)

如果是在Ansible自动化流程中实现,可直接通过内置lookup插件完成动态组装:

- name: 动态生成用户YAML
  hosts: localhost
  gather_facts: false
  tasks:
    - name: 解析textData.txt并组装用户列表
      set_fact:
        users: >-
          {{
            lookup('file', 'textData.txt').splitlines()
            | reject('eq', '')
            | map('split', ':', 1)
            | map('zip', ['userid', 'username'])
            | map('community.general.dict')
            | map('combine', {'something': false})
          }}
    - name: 写入最终YAML文件
      copy:
        content: |
          - name: "User Names"
            users: {{ users | to_nice_yaml(indent=2) | indent(width=4, firstline=true) }}
        dest: output.yaml

内容的提问来源于stack exchange,提问作者Aadhi Verma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 11:15:04