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的终止,以免发生费用。
相关推荐
心怀梦想的咸鱼几秒前
Ue5 umg学习(三)文本控件
学习·ue5
心怀梦想的咸鱼2 分钟前
Ue5 umg学习(二)图像控件,锚点
学习·ue5
小A1591 小时前
STM32完全学习——系统时钟设置
stm32·嵌入式硬件·学习
2301_775281191 小时前
柯桥生活英语口语学习“面坨了”英语怎么表达?
学习·生活
江梦寻1 小时前
思科模拟器路由器配置实验
开发语言·网络·网络协议·学习·计算机网络
金星娃儿2 小时前
MATLAB基础知识笔记——(矩阵的运算)
笔记·matlab·矩阵
一只特立独行的程序猿2 小时前
关于GCC内联汇编(也可以叫内嵌汇编)的简单学习
汇编·学习·gcc
虾球xz2 小时前
游戏引擎学习第10天
学习·游戏引擎
Chef_Chen2 小时前
从0开始学习机器学习--Day25--SVM作业
学习·机器学习·支持向量机
L_cl2 小时前
Python学习从0到1 day28 Python 高阶技巧 ⑧ 递归
学习