-1

Snippet of the .yml file:

- hosts: arbiters
  roles:
    - role: roles/arbiters
      vars:
        machines:
          arb-1:
            - repset: r-11
              mongoversion: 4.2
              port: 27017
            - repset: r-17
              mongoversion: 4.2
              port: 27018

I want to append sub-keys with values using Python:

            - repset: my_own_value
              mongoversion: 40000
              port: 1

The following code works partially

data[0]['roles'][0]['vars']['machines']['arb-2'] = dict(mongoversion='40000', port='1', repset='my_own_value')

gives

'arb-2': {'mongoversion': 40000,
          'port': '1',
          'repset': 'my_own_value'}

This is incorrect, as I want to append, instead of replace. When I use the += operator, instead of =, it gives:

'arb-2': [{'mongoversion': 4.2,
           'port': 27017,
           'repset': 'r-10'},
          {'mongoversion': 4.2,
           'port': 27018,
           'repset': 'r-16'},
           'mongoversion',
           'port',
           'repset']

Now, the values are missing. I've followed the answer as described here, and tried to play around with several settings, but I don't seem to succeed.

Anthon
  • 69,918
  • 32
  • 186
  • 246
Kevin C
  • 4,851
  • 8
  • 30
  • 64
  • Are you sure the file extension has to be `.yml`? For over 12 years the [officially recommended extension](https://web.archive.org/web/20060924190202/http://yaml.org/faq.html) for YAML files has been `.yaml` – Anthon Nov 14 '19 at 12:30
  • Irrelevant discussion for this question – Kevin C Nov 14 '19 at 12:48

1 Answers1

1

The problem is, your element ['arb-1'] isn't of type dict, it is of type list. So actually you should do the following:

data[0]['roles'][0]['vars']['machines']['arb-2'].append({'mongoversion'="v40000",'port'=1,'repset'="my_own_value"})

or in short

data["some"]["path"].append({'your':"object",'values':"here"})

-- edit --

Here is a complete test program. Dependency can be installed with pip install pyyaml.

import yaml

yaml_doc = """
  a: 1
  b:
    c:
      - a: b
        e: f
      - c: d
    d: 4
"""

doc = yaml.load(yaml_doc, Loader=yaml.FullLoader)

print(type(doc["b"]["c"]))
print doc

doc["b"]["c"].append({"x":2,"w":"i","u":'t'})
print doc
thetillhoff
  • 451
  • 4
  • 8