How to get ruamel yaml to indent nested sequences with 2 spaces

29 Views Asked by At

We are using ruamel.yaml (0.18.6), and want to indent sequences with two leading spaces. we noticed that it uses a 2-space indent on the first sequence, but switches to a 4-space indent on the second and subsequent levels. As shown below:

AWSTemplateFormatVersion: '2010-09-09'
Conditions:
  HA: !Equals
    - !FindInMap
        - Environments
        - !Ref 'Environment'
        - HighAvailability
    - 'true'

How can we configure ruamel.yaml to consistently indent nested sequences with 2 spaces?

We followed the recommended indent setting of (mapping=2, sequence=4, offset=2) as documented here.

The default format will indent the first level with 0 spaces, and subsequent sequences with 2 spaces as so:

AWSTemplateFormatVersion: '2010-09-09'
Conditions:
  HA: !Equals
  - !FindInMap
    - Environments
    - !Ref 'Environment'
    - HighAvailability
  - 'true'
1

There are 1 best solutions below

4
Anthon On

Both outputs that you show are consistently indented. The first one 4 positions with an offset of 2 for the dash for each of the sequences and the second one with 2 position and an offset of 0:

AWSTemplateFormatVersion: '2010-09-09'
Conditions:
  HA: !Equals
    - !FindInMap
        - Environments
        - !Ref 'Environment'
        - HighAvailability
    - 'true'
#       ^ two position offset of dash inner sequence
#     ^ beginning of 4 positions 
#   ^ two positions offset for dash outer sequence
# ^ beginning of 4 positions outer sequence 

For the second example there is no offset for the indent, that the inner sequence is further indented is a necessity to make it a nested sequence for the first element of the outer sequence:

AWSTemplateFormatVersion: '2010-09-09'
Conditions:
  HA: !Equals
  - !FindInMap
    - Environments
    - !Ref 'Environment'
    - HighAvailability
  - 'true'
#   ^ zero position offset of dash inner sequence
#   ^ beginning of 4 positions 
# ^ zero positions offset for dash outer sequence
# ^ beginning of 4 positions outer sequence 

The following would be inconsistent, because the outer sequence would have 4 positions with an offset of 2 and the inner 2 positions with an offset of 0

AWSTemplateFormatVersion: '2010-09-09'
Conditions:
  HA: !Equals
    - !FindInMap
      - Environments
      - !Ref 'Environment'
      - HighAvailability
    - 'true'
#     ^ zero position offset of dash inner sequence
#     ^ beginning of 2 positions 
#   ^ two positions offset for dash outer sequence
# ^ beginning of 4 positions outer sequence 

And ruamel.yaml cannot be used to generate such inconsistent formatting.