1

I want to write a script that imports data of a csv file with users and generates a yaml file used in ansible to create Linux users. The csv file is list with the following form:

users = [
  ['user1', 'passwordUser1' ['wheel', 'users']],
  ['user2', 'passwordUser2' ['wheel', 'users']],
  ...
]

The yaml file must have the following form:

users:
- name: user1
  groups: 
  - wheel
  - users
  password: passwordUser1
- name: user2
  groups: 
  - wheel
  - users
  password: passwordUser2
- ...

I have already found a source to export from a dictionary, but it reorders the fields alphabetically. (groups before name)

My code is the following:

import yaml

output = [{'users': [{'name': 'user1', 'groups': ['wheel', 'users'], 'password': 'user1p'}]}]

with open(r'/home/maarten/git/elnx-1920-sme-maartenbeeckmans/assignment/store_file.yaml', 'w') as file:
    documents = yaml.dump(output, file)

Yaml file it generates

- users:
  - groups:
    - wheel
    - users
    name: user1
    password: user1p
  • 2
    Duplicate of [Can PyYAML dump dict items in non-alphabetical order?](https://stackoverflow.com/questions/16782112/can-pyyaml-dump-dict-items-in-non-alphabetical-order/). – Vladimir Botka Nov 13 '19 at 02:17
  • 1
    Why is the order of the keys in a dictionary significant? – Vladimir Botka Nov 13 '19 at 02:23
  • 1
    Possible duplicate of [Can PyYAML dump dict items in non-alphabetical order?](https://stackoverflow.com/questions/16782112/can-pyyaml-dump-dict-items-in-non-alphabetical-order) – mdaniel Nov 13 '19 at 04:38
  • 1
    If you require the keys in a YAML mapping in a specific order, you violate the spec which says the order must not convey content information, i.e. the order of keys must be irrelevant to whatever you're doing. If it's not, YAML is not the right tool for the task. – flyx Nov 13 '19 at 09:12

0 Answers0