0

Say I have a YAML like:

Resources:
  AlarmTopic:
    Type: AWS::SNS::Topic
    Properties:
      Subscription:
        - !If
          - ShouldAlarm
            Protocol: email

How do I get each key and value of all the children if I'm walking over each resource and I want to know if one of the values may contain a certain string? I'm using PyYAML but I'm also open to using some other library.

Alper
  • 3,424
  • 4
  • 39
  • 45

1 Answers1

0

You can use the low-level event API if you only want to inspect scalar values:

import yaml
import sys

input = """
Resources:
  AlarmTopic:
    Type: AWS::SNS::Topic
    Properties:
      Subscription:
        - !If
          - ShouldAlarm
          - Protocol: email
"""

for e in yaml.parse(input):
    if isinstance(e, yaml.ScalarEvent):
        print(e.value)

(I fixed your YAML because it had a syntax error.) This yields:

Resources
AlarmTopic
Type
AWS::SNS::Topic
Properties
Subscription
ShouldAlarm
Protocol
email
flyx
  • 35,506
  • 7
  • 89
  • 126
  • But say I want to get everything under AlarmTopic, I could do that by doing `e["Resources"]["AlarmTopic"].value`? – Alper Jan 20 '22 at 10:08
  • @Alper No, this is an event-based API, not a structural API. You need to poll each event separately. What you'd do is to keep track of the „path“ you're currently in. [This question](https://stackoverflow.com/a/49360813/347964) shows an elaborate example on how to track paths with events (in that case, it appends events to a given path, easily adjustable to your needs). – flyx Jan 20 '22 at 10:15