<p>I need to compare yaml files that are generated from two different processes and are ordered differently and detect if they are logically the same ideally in python.</p>
<p>yaml file 1:</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80
</code></pre>
<p>yaml file 2:</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: nginx
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        ports:
        - containerPort: 80
        image: nginx:1.14.2
</code></pre>
<p>What's the best way to generate useful diffs of the yaml at the logical level vs the literal text level? In the toy example above these yaml files should be considered equivalent.</p>

John Drinane
<p>The best solution I was able to arrive at is below script.</p>
<pre><code>&quot;&quot;&quot;
python path_to_dir/compare_yaml.py path_to_dir/file1.yaml path_to_dir/file2.yaml
&quot;&quot;&quot;
import argparse
import yaml
import dictdiffer

parser = argparse.ArgumentParser(description='Convert two yaml files to dict and compare equality. Allows comparison of differently ordered keys.')
parser.add_argument('file_paths', type=str, nargs=2,
                    help='Full paths to yaml documents')
args = parser.parse_args()

print(f&quot;File Path 1: {args.file_paths[0]}&quot;)
print(f&quot;File Path 2: {args.file_paths[1]}&quot;)

with open(args.file_paths[0],'r') as rdr:
    data1=rdr.read()

with open(args.file_paths[1],'r') as rdr:
    data2=rdr.read()

data1_dict = yaml.load(data1,Loader=yaml.FullLoader)
data2_dict = yaml.load(data2,Loader=yaml.FullLoader)

if data1_dict == data2_dict:
    print(&quot;No difference detected&quot;)
else:
    print(&quot;Differences detected:&quot;)
    for diff in list(dictdiffer.diff(data1_dict, data2_dict)):
        print(diff)
</code></pre>
<p>If run against example in question as is:</p>
<pre><code>python .../compare_yaml.py .../yaml1.yaml .../yaml2.yaml
File Path 1: .../yaml1.yaml
File Path 2: .../yaml2.yaml
No difference detected
</code></pre>
<p>If change a key, then get output like this:</p>
<pre><code>python .../compare_yaml.py .../yaml1.yaml .../yaml2.yaml
File Path 1: .../yaml1.yaml
File Path 2: .../yaml2.yaml
Differences detected:
('change', ['spec', 'template', 'spec', 'containers', 0, 'name'], ('nginx', 'ngin'))
</code></pre>
