Using a proper YAML parser on the data in the question,
$ yq -y '(.. | .package? | select(has("state").state == "present")) |= (.use = "package_manager")' file.yml - name: Package X Install package: name: - package_1 - package_2 state: present use: package_manager - name: Package Y Install package: name: package_3 state: present use: package_manager - block: - name: Package Z Install package: name: package_4 state: present use: package_manager This uses the yq parser to add the use: package_manager key+value in each package section that contains a state key corresponding to the value present.
It does this by recursing over all the data, picking out the package sections that have a state key with the value present. It then adds the new key and value to those sections.