简体   繁体   中英

AWS Cloudformation JSON template to c# object

Does anyone know how to convert an AWS cloud formation son template into ac# object or custom class. I've deserialised json using a data contract before but I'm having trouble with the cloud formation template because each resource starts with a unique name so I'm not sure how to handle it. My aim is to compare a template with what is already live in AWS by putting the data from the API and the data from the template into a class and comparing them. If there's a better way please feel free to shoot me down. Here's and example cloud formation template.

{
  "AWSTemplateFormatVersion" : "2010-09-09",

  "Description" : "AWS CloudFormation Sample.",

  "Parameters" : {
    "KeyName": {
      "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance",
      "Type": "AWS::EC2::KeyPair::KeyName",
      "ConstraintDescription" : "must be the name of an existing EC2 KeyPair."
    },
  "Resources" : {  
    "SecurityGroup1" : {
      "Type" : "AWS::EC2::SecurityGroup",
      "Properties" : {
        "GroupDescription" : "Enable SSH access via port 22",
        "SecurityGroupIngress" : [ {
          "IpProtocol" : "tcp",
          "FromPort" : "22",
          "ToPort" : "22",
          "CidrIp" : { "Ref" : "SSHLocation"}
        } ]
      }
    },
    "SecurityGroup2" : {
      "Type" : "AWS::EC2::SecurityGroup",
      "Properties" : {
        "GroupDescription" : "Enable SSH access via port 22",
        "SecurityGroupIngress" : [ {
          "IpProtocol" : "tcp",
          "FromPort" : "22",
          "ToPort" : "22",
          "CidrIp" : { "Ref" : "SSHLocation"}
        } ]
      }
    }
  },
  "Outputs" : {    
    }
  }
}

The straightforward way would be to treat the Resources part of the template as a dictionary where the resource name is the key and its properties is the value:

class ResourceProperties
{
    public string GroupDescription { get; set; }
}

class Resource
{
    public string Type { get; set; }
    public ResourceProperties Properties { get; set; }
}

class Parameters
{
    public Dictionary<string, Resource> Resources { get; set; }
}

class Template
{
    public Parameters Parameters { get; set; }
}

(The rest of the fields is obvious)

And then using

var template = JsonConvert.DeserializeObject<Template>(json);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM