使用 python 将列表添加到(YAML)文本文件的特定行

使用 python 将列表添加到(YAML)文本文件的特定行

我有一个用于 NetBox 的 Ansible 模块文件,其内容如下:

- name: "Test NetBox modules"
  connection: local
  hosts: localhost
  gather_facts: False

  tasks:
    - name: Create device within NetBox with only required information
      netbox.netbox.netbox_device:
        netbox_url: http://netbox.local
        netbox_token: thisIsMyToken
        data:
          name: xxxx
          device_type: 
          device_role: 
          site: Main
        state: present


    - name: Create device within NetBox with only required information
      netbox.netbox.netbox_device:
        netbox_url: http://netbox.local
        netbox_token: thisIsMyToken
        data:
          name: xxxx
          device_type: 
          device_role: 
          site: Main
        state: present

    - name: Create device within NetBox with only required information
      netbox.netbox.netbox_device:
        netbox_url: http://netbox.local
        netbox_token: thisIsMyToken
        data:
          name: xxxx
          device_type: 
          device_role: 
          site: Main
        state: present

它有 3 个添加设备的任务。我有一个像这样的 Python 列表:['switch1', 'switch2', 'switch3']

我的问题是,如何在列表前面添加这个元素,name: xxxx而不是xxxx经常使用 python?

答案1

我不会使用 Python 来完成这项任务(工作量太大,重复做事)...我将使用支持存储数据集的专门的文本处理工具,例如数组awk

awk -F'[ ]' 'BEGIN {
    devices[1] = "switch1"
    devices[2] = "switch2"
    devices[3] = "switch3"
}

/name: xxxx/ {
    i++
    $NF = devices[i]
}

{
    print
}' file.yaml

输出结果为:

- name: "Test NetBox modules"
  connection: local
  hosts: localhost
  gather_facts: False

  tasks:
    - name: Create device within NetBox with only required information
      netbox.netbox.netbox_device:
        netbox_url: http://netbox.local
        netbox_token: thisIsMyToken
        data:
          name: switch1
          device_type: 
          device_role: 
          site: Main
        state: present


    - name: Create device within NetBox with only required information
      netbox.netbox.netbox_device:
        netbox_url: http://netbox.local
        netbox_token: thisIsMyToken
        data:
          name: switch2
          device_type: 
          device_role: 
          site: Main
        state: present

    - name: Create device within NetBox with only required information
      netbox.netbox.netbox_device:
        netbox_url: http://netbox.local
        netbox_token: thisIsMyToken
        data:
          name: switch3
          device_type: 
          device_role: 
          site: Main
        state: present

或者gawk编辑文件:

gawk -i inplace -F'[ ]' 'BEGIN {
        devices[1] = "switch1"
        devices[2] = "switch2"
        devices[3] = "switch3"
}

/name: xxxx/ {
        i++
        $NF = devices[i]
}

{
        print
}' file.yaml

注意:你仍然可以在 Python 脚本中调用awk或,gawk例如 Python 的子进程或者操作系统模块。

相关内容