我想即时附加/分离EC2实例的IAM配置文件。我编写的代码无法执行循环。
它仅将IAM配置文件与第一个ec2实例相关联并出现。
// import entire SDK
var AWS = require('aws-sdk');
// import AWS object without services
var AWS = require('aws-sdk/global');
var ec2 = new AWS.EC2({region: 'us-east-1'});
var instancesProfile = '';
ec2.describeIamInstanceProfileAssociations(function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
for (var p in data.IamInstanceProfileAssociations){
var association = data.IamInstanceProfileAssociations[p].AssociationId
var instance = data.IamInstanceProfileAssociations[p].InstanceId
instancesProfile +='InstanceId:' + instance + ' AssociationId: ' + association + '\n';
//console.log(association);
if (association === '')
{
var params = {
IamInstanceProfile: {
Name: "S3FullAccess"
},
InstanceId: instance
};
ec2.associateIamInstanceProfile(params,function(err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});
} else
{
var params = {
IamInstanceProfile: {
Name: "S3FullAccess"
},
AssociationId: association
};
ec2.replaceIamInstanceProfileAssociation(params,function(err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});
};
console.log(instancesProfile);
}
});