aws(学习笔记第二课) AWS SDK(node js)

aws(学习笔记第二课)

  • 使用AWS SDK(node js)

学习内容:

  • 使用AWS SDK(node js)

1. AWS SDK(node js)

  1. AWS支持多种SDK开发(除了AWS CLI,还支持其他的SDK)

    • Android
    • Python
    • Node.js(Javascript)
    • Java
    • Browsers(Javascript)
    • Ruby
    • PHP
    • .NET
    • IOS
    • Go
  2. 使用Node.js来控制AWS

    • 安装Node.js

      这是前提条件,这里采用windows + git bash的方式练习,首先安装Node.js

    • Node.js的程序结构

    • package.json

      这里定义了nodecc所需要的依赖包。

      json 复制代码
      {
      	"dependencies": {
      		"aws-sdk": "2.1.18",
      		"blessed": "0.0.51",
      		"jmespath": "0.10.0"
      	},
      	"private": true
      }
    • index.js

      这个是main程序入口,定义了以下的功能

      • listServer(list servers 展示所有的ec2 server列表)
      • listAMIs.js(create server 创建ec2 server)
      • listServers.js( terminate server 终止ec2 server)
    • \lib下的各个*.js

      • createServer.js 创建ec2 server
        注意,这里的KeyName一定要和前面设定的密钥对名字一致。
      • listAMIs.js 列出全部可用ami
      • listServers.js 列出全部可用ec2 server
      • listSubnets.js 列出全部可用subnet
      • showServer.js 列出所有创建的ec2 server
      • terminateServer.js 终止列出的ec2 server
    • index.js以及各个lib/*.js

      • index.js

        javascript 复制代码
        var blessed = require('blessed');
        
        var screen = blessed.screen({
        	autoPadding: true,
        	smartCSR: true,
        	log: "./nodecc.log"
        });
        
        screen.title = 'Node Control Center for AWS';
        
        var content = blessed.box({  
        	parent: screen,
        	width: '70%',
        	height: '90%',
        	top: '10%',
        	left: '30%',
        	border: {
        		type: 'none',
        		fg: '#ffffff'
        	},
        	fg: 'white',
        	bg: 'blue',
        	content: '{bold}Node Control Center for AWS{/bold}\n\nPlease select one of the actions from the left and press return.\n\nYou can always go back with the left arrow key.\n\nYou can terminate the application by pressing ESC or q.',
        	tags: true
        });
        
        var progress = blessed.progressbar({
        	parent: screen,
        	width: '70%',
        	height: '10%',
        	top: '0%',
        	left: '30%',
        	orientation: 'horizontal',
        	border: {
        		type: 'line',
        		fg: '#ffffff'
        	},
        	fg: 'white',
        	bg: 'blue',
        	barFg: 'green',
        	barBg: 'green',
        	filled: 0
        });
        
        var list = blessed.list({  
        	parent: screen,
        	width: '30%',
        	height: '100%',
        	top: '0%',
        	left: '0%',
        	border: {
        		type: 'line',
        		fg: '#ffffff'
        	},
        	fg: 'white',
        	bg: 'blue',
        	selectedBg: 'green',
        	mouse: true,
        	keys: true,
        	vi: true,
        	label: 'actions',
        	items: ['list servers', 'create server', 'terminate server']
        });
        list.on('select', function(ev, i) {
        	content.border.type = 'line';
        	content.focus();
        	list.border.type = 'none';
        	open(i);
        	screen.render(); 
        });
        list.focus();
        
        function open(i) {
        	screen.log('open(' + i + ')');
        	if (i === 0) {
        		loading();
        		require('./lib/listServers.js')(function(err, instanceIds) {
        			loaded();
        			if (err) {
        				log('error', 'listServers cb err: ' + err);
        			} else {
        				var instanceList = blessed.list({
        					fg: 'white',
        					bg: 'blue',
        					selectedBg: 'green',
        					mouse: true,
        					keys: true,
        					vi: true,
        					items: instanceIds
        				});
        				content.append(instanceList);
        				instanceList.focus();
        				instanceList.on('select', function(ev, i) {
        					loading();
        					require('./lib/showServer.js')(instanceIds[i], function(err, instance) {
        						loaded();
        						if (err) {
        							log('error', 'showServer cb err: ' + err);
        						} else {
        							var serverContent = blessed.box({  
        								fg: 'white',
        								bg: 'blue',
        								content:
        									'InstanceId: ' + instance.InstanceId + '\n' +
        									'InstanceType: ' + instance.InstanceType + '\n' +
        									'LaunchTime: ' + instance.LaunchTime + '\n' +
        									'ImageId: ' + instance.ImageId + '\n' +
        									'PublicDnsName: ' + instance.PublicDnsName
        							});
        							content.append(serverContent);
        						}
        						screen.render(); 
        					});
        				});
        				screen.render(); 
        			}
        			screen.render(); 
        		});
        	} else if (i === 1) {
        		loading();
        		require('./lib/listAMIs.js')(function(err, result) {
        			loaded();
        			if (err) {
        				log('error', 'listAMIs cb err: ' + err);
        			} else {
        				var amiList = blessed.list({
        					fg: 'white',
        					bg: 'blue',
        					selectedBg: 'green',
        					mouse: true,
        					keys: true,
        					vi: true,
        					items: result.descriptions
        				});
        				content.append(amiList);
        				amiList.focus();
        				amiList.on('select', function(ev, i) {
        					var amiId = result.amiIds[i];
        					loading();
        					require('./lib/listSubnets.js')(function(err, subnetIds) {
        						loaded();
        						if (err) {
        							log('error', 'listSubnets cb err: ' + err);
        						} else {
        							var subnetList = blessed.list({
        								fg: 'white',
        								bg: 'blue',
        								selectedBg: 'green',
        								mouse: true,
        								keys: true,
        								vi: true,
        								items: subnetIds
        							});
        							content.append(subnetList);
        							subnetList.focus();
        							subnetList.on('select', function(ev, i) {
        								loading();
        								require('./lib/createServer.js')(amiId, subnetIds[i], function(err) {
        									loaded();
        									if (err) {
        										log('error', 'createServer cb err: ' + err);
        									} else {
        										var serverContent = blessed.box({  
        											fg: 'white',
        											bg: 'blue',
        											content: 'starting ...'
        										});
        										content.append(serverContent);
        									}
        									screen.render(); 
        								});
        							});
        							screen.render(); 
        						}
        						screen.render(); 
        					});
        				});
        				screen.render(); 
        			}
        			screen.render(); 
        		});
        	} else if (i === 2) {
        		loading();
        		require('./lib/listServers.js')(function(err, instanceIds) {
        			loaded();
        			if (err) {
        				log('error', 'listServers cb err: ' + err);
        			} else {
        				var instanceList = blessed.list({
        					fg: 'white',
        					bg: 'blue',
        					selectedBg: 'green',
        					mouse: true,
        					keys: true,
        					vi: true,
        					items: instanceIds
        				});
        				content.append(instanceList);
        				instanceList.focus();
        				instanceList.on('select', function(ev, i) {
        					loading();
        					require('./lib/terminateServer.js')(instanceIds[i], function(err) {
        						loaded();
        						if (err) {
        							log('error', 'terminateServer cb err: ' + err);
        						} else {
        							var serverContent = blessed.box({  
        								fg: 'white',
        								bg: 'blue',
        								content: 'terminating ...'
        							});
        							content.append(serverContent);
        						}
        						screen.render(); 
        					});
        				});
        				screen.render(); 
        			}
        			screen.render(); 
        		});
        	} else {
        		log('error', 'not supported');
        		screen.render(); 
        	}
        }
        
        screen.key('left', function(ch, key) {  
        	content.border.type = 'none';
        	content.children.slice().forEach(function(child) {
        		content.remove(child);
        	});
        	list.border.type = 'line';
        	list.focus();
        	screen.render(); 
        });
        
        screen.key(['escape', 'q', 'C-c'], function(ch, key) { 
        	return process.exit(0);
        });
        
        var loadingInterval;
        
        function loading() {
        	progress.reset();
        	clearInterval(loadingInterval);
        	loadingInterval = setInterval(function() {
        		if (progress.filled < 75) {
        			progress.progress(progress.filled + 5);
        		}
        		screen.render(); 
        	}, 200);
        }
        
        function loaded() {
        	clearInterval(loadingInterval);
        	progress.progress(100);
        	screen.render(); 
        }
        
        function log(level, message) {
        	screen.log('[' + level + ']: ' + message);
        }
        
        screen.render(); 
    • /lib/createServer.js

      javascript 复制代码
      var AWS = require('aws-sdk');
      var ec2 = new AWS.EC2({
      	"region": "ap-northeast-1"
      });
      
      module.exports = function(amiId, subnetId, cb) {
      	ec2.runInstances({
      		"ImageId": amiId,
      		"MinCount": 1,
      		"MaxCount": 1,
      		"KeyName": "my-cli-key",
      		"InstanceType": "t2.micro",
      		"SubnetId": subnetId
      	}, function(err) {
      		if (err) {
      			cb(err);
      		} else {
      			cb(null);
      		}
      	});
      };
    • /lib/listAMIs.js

      javascript 复制代码
      var jmespath = require('jmespath');
      var AWS = require('aws-sdk');
      var ec2 = new AWS.EC2({
      	"region": "ap-northeast-1"
      });
      
      module.exports = function(cb) {
      	ec2.describeImages({
      		"Filters": [{
      			"Name": "description",
      			"Values": ["Amazon Linux AMI *"]
      		}]
      	}, function(err, data) {
      		if (err) {
      			cb(err);
      		} else {
      			var amiIds = jmespath.search(data, 'Images[*].ImageId');
      			var descriptions = jmespath.search(data, 'Images[*].Description');
      			cb(null, {"amiIds": amiIds, "descriptions": descriptions});
      		}
      	});
      };
    • /lib/listServers.js

      javascript 复制代码
      var jmespath = require('jmespath');
      var AWS = require('aws-sdk');
      var ec2 = new AWS.EC2({
      	"region": "ap-northeast-1"
      });
      
      module.exports = function(cb) {
      	ec2.describeInstances({
      		"Filters": [{
      			"Name": "instance-state-name",
      			"Values": ["pending", "running"]
      		}],
      		"MaxResults": 10
      	}, function(err, data) {
      		if (err) {
      			cb(err);
      		} else {
      			var instanceIds = jmespath.search(data, 'Reservations[].Instances[].InstanceId');
      			cb(null, instanceIds);
      		}
      	});
      };
    • /lib/listSubnets.js 注意,这里默认的vpc

      javascript 复制代码
      var jmespath = require('jmespath');
      var AWS = require('aws-sdk');
      var ec2 = new AWS.EC2({
      	"region": "ap-northeast-1"
      });
      
      module.exports = function(cb) {
      	ec2.describeVpcs({
      		"Filters": [{
      			"Name": "isDefault",
      			"Values": ["true"]
      		}]
      	}, function(err, data) {
      		if (err) {
      			cb(err);
      		} else {
      			var vpcId = data.Vpcs[0].VpcId;
      			ec2.describeSubnets({
      				"Filters": [{
      					"Name": "vpc-id",
      					"Values": [vpcId]
      				}]
      			}, function(err, data) {
      				if (err) {
      					cb(err);
      				} else {
      					var subnetIds = jmespath.search(data, 'Subnets[*].SubnetId');
      					cb(null, subnetIds);
      				}
      			});
      		}
      	});
      };
    • /lib/showServer.js

      javascript 复制代码
      var AWS = require('aws-sdk');
      var ec2 = new AWS.EC2({
      	"region": "ap-northeast-1"
      });
      
      module.exports = function(instanceId, cb) {
      	ec2.describeInstances({
      		"InstanceIds": [instanceId]
      	}, function(err, data) {
      		if (err) {
      			cb(err);
      		} else {
      			cb(null, data.Reservations[0].Instances[0]);
      		}
      	});
      };
    • /lib/terminateServer.js

      javascript 复制代码
      var AWS = require('aws-sdk');
      var ec2 = new AWS.EC2({
      	"region": "ap-northeast-1"
      });
      
      module.exports = function(instanceId, cb) {
      	ec2.terminateInstances({
      		"InstanceIds": [instanceId]
      	}, function(err) {
      		if (err) {
      			cb(err);
      		} else {
      			cb(null);
      		}
      	});
      };
    • 启动Node.jsAWS SDK的应用程序nodecc press escape key to exit

      shell 复制代码
      npm install
      node index.js
  3. 使用应用程序nodecc控制AWS

    • 启动主程序,创建ec2 server
      create server-> 选择Amazon Linux AMI 2018.03.0.20230322.0这个ami注意,这里的InstanceType: t2micro,会导致一些ami会创建ec2 server失败
    • 进入主菜单(left key to return main menu in the left),进入list servers
    • 选择subnet
      这里存在唯一default subnet,因此就显示一个subnet
    • 创建了ec2 server之后,进入list server进行检查
      注意,可以在create server的同时,执行tail -f nodecc.log,因为可能有些原因,导致create server失败
    • 进入AWS Console进行检查
    • 登录创建的ec2 server
    • 及时终止创建的ec2 server
      练习完毕,利用terminate server进行ec2 server的终止,以免发生费用。
相关推荐
biter008813 分钟前
opencv(15) OpenCV背景减除器(Background Subtractors)学习
人工智能·opencv·学习
车轮滚滚__23 分钟前
uniapp对接unipush 1.0 ios/android
笔记
Code哈哈笑1 小时前
【Java 学习】深度剖析Java多态:从向上转型到向下转型,解锁动态绑定的奥秘,让代码更优雅灵活
java·开发语言·学习
QQ同步助手2 小时前
如何正确使用人工智能:开启智慧学习与创新之旅
人工智能·学习·百度
流浪的小新2 小时前
【AI】人工智能、LLM学习资源汇总
人工智能·学习
A懿轩A3 小时前
C/C++ 数据结构与算法【数组】 数组详细解析【日常学习,考研必备】带图+详细代码
c语言·数据结构·c++·学习·考研·算法·数组
云边有个稻草人3 小时前
【优选算法】—复写零(双指针算法)
笔记·算法·双指针算法
南宫生11 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
sanguine__11 小时前
Web APIs学习 (操作DOM BOM)
学习
冷眼看人间恩怨11 小时前
【Qt笔记】QDockWidget控件详解
c++·笔记·qt·qdockwidget