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的终止,以免发生费用。
相关推荐
wyn200011283 小时前
KafKa学习笔记
笔记·学习·kafka
ihaveadream丶4 小时前
Oracle中快速排查存储过程问题
笔记·oracle
幸运狗头7 小时前
Linux学习-基于TCP实现群聊
linux·学习·tcp/ip·群聊
KFCcrazy47 小时前
嵌入式学习日记(36)TCP并发服务器构建——epoll
服务器·学习·tcp/ip
diablobaal9 小时前
云计算学习100天-第28天
运维·服务器·学习
F_D_Z10 小时前
人工智能基础概念
笔记
艾莉丝努力练剑10 小时前
【C语言16天强化训练】从基础入门到进阶:Day 11
c语言·学习·算法
像素之间10 小时前
nginx的诞生背景、核心优势、与 Apache 的对比
运维·学习·nginx
幸运狗头12 小时前
Linux学习-TCP并发服务器构建
linux·服务器·学习
The_Second_Coming13 小时前
最小化 CentOS 模板虚拟机安装与配置
linux·运维·服务器·学习·centos·云计算