Search code examples
pythonlistdictionarypyyaml

How to extract values from list python?


I'm working with pyyaml and i need to describe the server configurations in yaml, then run script with arguments from this list:

servers:
  - server: server1
    hostname: test.hostname
    url: http://test.com
    users:
    - username: test
      password: pass
    - username: test1
      password: pass2
  - server: server2
    hostname: test.hostname2
    url: http://test2.com
    users:
    - username: test3
      password: pass
    - username: test4
      password: pass2
    - username: test5
      password: pass6
...

then I'm getting this data from yaml:

source = self._tree_read(src, tree_path)

and then I'm calling bash script with args from this list:

for s in source['servers']:
    try:
        subprocess.call(["/bin/bash", "./servers.sh",
                         s["server"],
                         s["hostname"],
                         s["url"],
                       **s["users"]**
                        ], shell=False)

How can I pass users in this case? The number of users can be different for each server and I need to pass it as args somehow. Or may be is it possible to put usernames from each server to list, and do same with passwords and then pass it it as 2 args with 2 lists?


Solution

  • you could add a variable to hold the users:

    for s in source["servers"]:
        # add any processing in the list comp to extract users
        user_list = [user["username"] for user in s["users"]]
        try:
            subprocess.call(["/bin/bash", "./servers.sh",
                             s["server"],
                             s["hostname"],
                             s["url"],
                             ",".join(user_list),
                             ], shell=False)
    

    You'll need to modify the listcomp to extract the fields you want from s["users"].