I wouldn't use Python for this task (too much work and reinventing the wheel) ... I would use a specialized text processing tool that supports storing data sets e.g. arrays like awk
:
awk -F'[ ]' 'BEGIN {
devices[1] = "switch1"
devices[2] = "switch2"
devices[3] = "switch3"
}
/name: xxxx/ {
i++
$NF = devices[i]
}
{
print
}' file.yaml
which will output:
- 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
or gawk
to edit the file in place:
gawk -i inplace -F'[ ]' 'BEGIN {
devices[1] = "switch1"
devices[2] = "switch2"
devices[3] = "switch3"
}
/name: xxxx/ {
i++
$NF = devices[i]
}
{
print
}' file.yaml
Notice: You can still call awk
or gawk
from within a Python script with e.g. Python's subprocess or os modules.