kristofwillen / cfntagger

Mass tag resources in Cloudformation templates
GNU General Public License v3.0
4 stars 0 forks source link

cfntagger sometimes drops comments #1

Open kristofwillen opened 2 years ago

kristofwillen commented 2 years ago

Take this cfn template:

---
AWSTemplateFormatVersion: 2010-09-09
Description: Creates EC2 instances
# Top line of comment
Resources:
  # Line of comment in resource
  NOkEC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t3.nano
      ImageId: ami-deadbeef

Result of cfntagger:

---
AWSTemplateFormatVersion: 2010-09-09
Description: Creates EC2 instances
# Top line of comment
Resources:
  NOkEC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t3.nano
      ImageId: ami-deadbeef
      Tags:
      - Key: Owner
        Value: John

The line of comments in the resource block has been dropped.

kristofwillen commented 2 years ago

Seems an issue with ruamel, cfr bugreport #421

kristofwillen commented 2 years ago

Not sure if this is really related to ruamel; this code works perfectly:

import sys
import ruamel.yaml

from collections import OrderedDict
yaml_str = """---
AWSTemplateFormatVersion: 2010-09-09
Description: Creates EC2 instances

# Line 1 of comments to keep 1/1
Resources:
  # Line 2 of comments to keep - OkInstance2
  OkEC2Instance: # Line 3 of inline to keep 1/1
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: c3.xlarge
      ImageId: ami-deadbeef
      Tags:
        - Key: Creator
          Value: kristof
        - Key: Tester
          Value: Dinesh

  # Line 4 of comments to keep - OkInstance3 1/2
  # Line 5 of comments to keep - OkInstance3 2/2
  NOkEC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      # Line 6 of comments to keep - tagging 1/1
      InstanceType: t3.nano
      ImageId: ami-deadbeef
"""

yaml = ruamel.yaml.YAML()  

code = yaml.load(yaml_str)
code['Resources']['NOkEC2Instance']['Type'] = 'AWS::EC2::Foo'
code['Resources']['NOkEC2Instance']['Properties']['FooAttr'] = 'FooValue'
code['Resources']['OkEC2Instance']['Properties']['Tags'].append(OrderedDict({'Key': 'Team', 'Value': 'FooLawyers'}))

results in

  OkEC2Instance: # Line 3 of inline to keep 1/1
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: c3.xlarge
      ImageId: ami-deadbeef
      Tags:
      - Key: Creator
        Value: kristof
      - Key: Tester
        Value: Dinesh

  # Line 4 of comments to keep - OkInstance3 1/2
  # Line 5 of comments to keep - OkInstance3 2/2
      - Key: Team
        Value: FooLawyers
  NOkEC2Instance:
    Type: AWS::EC2::Foo
    Properties:
...
      # Line 6 of comments to keep - tagging 1/1
      InstanceType: t3.nano
      ImageId: ami-deadbeef
      FooAttr: FooValue

which seems completely correct...