首页 > 解决方案 > 是否可以通过 javascript 通过读取 json 文件而不是使用参数来更新安全组?

问题描述

我想通过让我的 javascript 文件从单独的 json 文件中读取信息来更新安全组规则,而不必使用 json 参数。

既然我已经使用 json 参数来更新安全组,我已经开始学习如何通过让 javascript/node.js 读取文件来使用 json 文件进行更新。

这是我使用过的建议代码:

var AWS = require('aws-sdk');

AWS.config.update({region: 'us-east-1'});

var fs = require('fs');

var filename = 'sg-0136a8e42bc076309Ingress.json';

var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});

ec2.updateSecurityGroupRuleDescriptionsIngress(filename, function(err, data) {
    if (err) {
        console.log("Failed to retrieve information", err);
        return; 
    }
    console.log("Information updated!");

    fs.readFile(filename, (err, data) => {
        if(err) console.log("Failed to output into file", err);
    });

});

以下是 JSON 参数:

GroupId: "sg-0136a8e42bc076309",
IpPermissions: [
    {
        FromPort: 139,
        IpProtocol: "tcp",
        IpRanges: [
            {
                CidrIp: "0.0.0.0/0",
                Description: "NetBIOS Session Service"
            }
        ],
        ToPort: 139
    }
]

但是,结果,我只收到一条错误消息:

Failed to retrieve information { MultipleValidationErrors: There were 34 validation errors:
* InvalidParameterType: Expected params to be a structure
* MissingRequiredParameter: Missing required key 'IpPermissions' in params

这是错误的一个例子。如何通过让 javascript 读取 json 文件而不会出现错误来更新安全组?

标签: javascriptnode.jsjsonamazon-ec2aws-sdk

解决方案


我认为您不应该在变量中写入文件名var filename = 'sg-0136a8e42bc076309Ingress.json'并将其设置为ec2.updateSecurityGroupRuleDescriptionsIngress函数的参数。您可以只需要 JSON 文件并作为参数提供功能

var file = require("./sg-0136a8e42bc076309Ingress.json");
ec2.updateSecurityGroupRuleDescriptionsIngress(file, function(err, data) {
     if (err) {
         console.log("Failed to retrieve information", err);
         return; 
     }
     console.log("Information updated!");
});

另外,你的另一件事,在这种情况下,你的功能fs.readFile是没用的。


推荐阅读