├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── aws-slack-bot.json ├── aws.go ├── aws_test.go ├── cmds └── aws.bash ├── main.go ├── main_test.go └── template.yml /.gitignore: -------------------------------------------------------------------------------- 1 | .gun 2 | Gunfile 3 | packaged.yml 4 | main 5 | main.zip 6 | insatnces.gob 7 | Gunfile.* 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: help 2 | #AWS_STACK_NAME=lalyos-lambda-go 3 | #AWS_S3_BUCKET=lp-lambda-go 4 | VERSION = 0.0.7 5 | 6 | help: ## Generates this help message 7 | @grep -E '^[0-9a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' 8 | 9 | zip: # builds the linux binary, and creates the zip for lambda upload 10 | GOOS=linux go build -o main -ldflags '-X main.Version="$(VERSION)"' main.go aws.go 11 | aws cloudformation package --template-file template.yml --s3-bucket $(AWS_S3_BUCKET) --output-template-file packaged.yml 12 | 13 | build-osx: 14 | go build -o main -ldflags '-X main.Version="$(VERSION)"' main.go aws.go 15 | 16 | update-fn-code: zip ## Updates the lambda code in the existing CF stack 17 | aws lambda update-function-code --function-name $(shell aws cloudformation list-stack-resources --stack-name $(AWS_STACK_NAME) --query 'StackResourceSummaries[?ResourceType == `AWS::Lambda::Function`].PhysicalResourceId' --out text) \ 18 | --s3-bucket $(AWS_S3_BUCKET) \ 19 | --s3-key $(shell sed -n '/CodeUri/ s:.*/::p' packaged.yml) 20 | 21 | deploy-stack: zip ## Deploys/Updates the cloudformation stack 22 | aws cloudformation deploy \ 23 | --stack-name $(AWS_STACK_NAME) \ 24 | --template-file ./packaged.yml \ 25 | --capabilities CAPABILITY_IAM 26 | 27 | print-api-url: ## Prints ApiGateway url base 28 | @aws cloudformation describe-stacks \ 29 | --stack-name $(AWS_STACK_NAME) \ 30 | --query 'Stacks[0].Outputs[0].OutputValue' \ 31 | --out text 32 | 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## lambda-slack-bot 2 | 3 | A Golang AWS Lambda to list running EC2 instanes - used by a Slack bot, to better control AWS spendings. For further details reads this [post](https://banzaicloud.com/blog/slackbot/). 4 | 5 | ## Compile 6 | 7 | ``` 8 | GOOS=linux go build -o main 9 | ``` 10 | 11 | ## Deployment 12 | 13 | ``` 14 | export AWS_STACK_NAME=lalyos-lambda-go 15 | export AWS_S3_BUCKET=lp-lambda-go 16 | 17 | aws cloudformation package --template-file template.yml --s3-bucket $AWS_S3_BUCKET --output-template-file packaged.yml 18 | aws cloudformation deploy --template-file ./packaged.yml --stack-name $AWS_STACK_NAME --capabilities CAPABILITY_IAM 19 | ``` 20 | 21 | ## Invoke API 22 | 23 | ``` 24 | AWS_API_ID=$(aws apigateway get-rest-apis --query 'items[? name == `'$AWS_STACK_NAME'`].id' --out text) 25 | AWS_STAGE=$(aws apigateway get-stages --rest-api-id $AWS_API_ID --query 'item[0].stageName' --out text) 26 | 27 | curl https://$AWS_API_ID.execute-api.$AWS_DEFAULT_REGION.amazonaws.com/$AWS_STAGE/ -d geza 28 | ``` 29 | 30 | ## List stacks 31 | 32 | ``` 33 | aws cloudformation list-stacks \ 34 | --stack-status-filter CREATE_COMPLETE \ 35 | --query StackSummaries[].StackName \ 36 | --out table 37 | ``` 38 | 39 | list lambda fn in stack 40 | ``` 41 | aws cloudformation list-stack-resources \ 42 | --stack-name $AWS_STACK_NAME \ 43 | --query 'StackResourceSummaries[?ResourceType == `AWS::Lambda::Function`].PhysicalResourceId' \ 44 | --out text 45 | ``` 46 | 47 | list all resorces: 48 | ``` 49 | aws cloudformation list-stack-resources \ 50 | --stack-name $AWS_STACK_NAME \ 51 | --query 'StackResourceSummaries[].[ResourceType,PhysicalResourceId,LogicalResourceId]' \ 52 | --out table 53 | ``` 54 | 55 | list regions: 56 | ``` 57 | aws ec2 describe-regions \ 58 | --query 'join(`,`, Regions[].RegionName | sort(@))' \ 59 | --out text 60 | ``` 61 | 62 | exclude one: 63 | ``` 64 | aws ec2 describe-regions \ 65 | --query 'join(`,`, Regions[? RegionName != `ap-northeast-2`].RegionName | sort(@))' \ 66 | --out text 67 | ``` 68 | -------------------------------------------------------------------------------- /aws-slack-bot.json: -------------------------------------------------------------------------------- 1 | { 2 | "AWSTemplateFormatVersion": "2010-09-09", 3 | "Outputs": { 4 | "RestUrl": { 5 | "Description": "External Rest Api url", 6 | "Value": { 7 | "Fn::Join": [ 8 | "", 9 | [ 10 | "https://", 11 | { 12 | "Ref": "ServerlessRestApi" 13 | }, 14 | ".execute-api.", 15 | { 16 | "Ref": "AWS::Region" 17 | }, 18 | ".amazonaws.com/", 19 | { 20 | "Ref": "ServerlessRestApiProdStage" 21 | } 22 | ] 23 | ] 24 | } 25 | } 26 | }, 27 | "Resources": { 28 | "HelloFunctionRole": { 29 | "Type": "AWS::IAM::Role", 30 | "Properties": { 31 | "ManagedPolicyArns": [ 32 | "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", 33 | "arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess" 34 | ], 35 | "AssumeRolePolicyDocument": { 36 | "Version": "2012-10-17", 37 | "Statement": [ 38 | { 39 | "Action": [ 40 | "sts:AssumeRole" 41 | ], 42 | "Effect": "Allow", 43 | "Principal": { 44 | "Service": [ 45 | "lambda.amazonaws.com" 46 | ] 47 | } 48 | } 49 | ] 50 | } 51 | } 52 | }, 53 | "ServerlessRestApiDeploymentb01515674b": { 54 | "Type": "AWS::ApiGateway::Deployment", 55 | "Properties": { 56 | "RestApiId": { 57 | "Ref": "ServerlessRestApi" 58 | }, 59 | "Description": "RestApi deployment id: b01515674ba137b5a8d155a800f475a68d0cc3a6", 60 | "StageName": "Stage" 61 | } 62 | }, 63 | "ServerlessRestApiProdStage": { 64 | "Type": "AWS::ApiGateway::Stage", 65 | "Properties": { 66 | "DeploymentId": { 67 | "Ref": "ServerlessRestApiDeploymentb01515674b" 68 | }, 69 | "RestApiId": { 70 | "Ref": "ServerlessRestApi" 71 | }, 72 | "StageName": "Prod" 73 | } 74 | }, 75 | "HelloFunctionSlackPostPermissionTest": { 76 | "Type": "AWS::Lambda::Permission", 77 | "Properties": { 78 | "Action": "lambda:invokeFunction", 79 | "Principal": "apigateway.amazonaws.com", 80 | "FunctionName": { 81 | "Ref": "HelloFunction" 82 | }, 83 | "SourceArn": { 84 | "Fn::Sub": [ 85 | "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/POST/", 86 | { 87 | "__Stage__": "*", 88 | "__ApiId__": { 89 | "Ref": "ServerlessRestApi" 90 | } 91 | } 92 | ] 93 | } 94 | } 95 | }, 96 | "HelloFunctionVersionPermissionProd": { 97 | "Type": "AWS::Lambda::Permission", 98 | "Properties": { 99 | "Action": "lambda:invokeFunction", 100 | "Principal": "apigateway.amazonaws.com", 101 | "FunctionName": { 102 | "Ref": "HelloFunction" 103 | }, 104 | "SourceArn": { 105 | "Fn::Sub": [ 106 | "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/GET/version", 107 | { 108 | "__Stage__": "Prod", 109 | "__ApiId__": { 110 | "Ref": "ServerlessRestApi" 111 | } 112 | } 113 | ] 114 | } 115 | } 116 | }, 117 | "HelloFunctionRootPermissionProd": { 118 | "Type": "AWS::Lambda::Permission", 119 | "Properties": { 120 | "Action": "lambda:invokeFunction", 121 | "Principal": "apigateway.amazonaws.com", 122 | "FunctionName": { 123 | "Ref": "HelloFunction" 124 | }, 125 | "SourceArn": { 126 | "Fn::Sub": [ 127 | "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/GET/", 128 | { 129 | "__Stage__": "Prod", 130 | "__ApiId__": { 131 | "Ref": "ServerlessRestApi" 132 | } 133 | } 134 | ] 135 | } 136 | } 137 | }, 138 | "HelloFunction": { 139 | "Type": "AWS::Lambda::Function", 140 | "Properties": { 141 | "Code": { 142 | "S3Bucket": "lp-lambda-go", 143 | "S3Key": "8c49a47a4dccf43893028d0546d17c0d" 144 | }, 145 | "Tags": [ 146 | { 147 | "Value": "SAM", 148 | "Key": "lambda:createdBy" 149 | } 150 | ], 151 | "Environment": { 152 | "Variables": { 153 | "REGIONS": "eu-west-1,eu-west-2,eu-west-3,eu-central-1,us-east-1,us-east-2,us-west-1,us-west-2" 154 | } 155 | }, 156 | "Handler": "main", 157 | "Role": { 158 | "Fn::GetAtt": [ 159 | "HelloFunctionRole", 160 | "Arn" 161 | ] 162 | }, 163 | "Runtime": "go1.x" 164 | } 165 | }, 166 | "HelloFunctionSlackPostPermissionProd": { 167 | "Type": "AWS::Lambda::Permission", 168 | "Properties": { 169 | "Action": "lambda:invokeFunction", 170 | "Principal": "apigateway.amazonaws.com", 171 | "FunctionName": { 172 | "Ref": "HelloFunction" 173 | }, 174 | "SourceArn": { 175 | "Fn::Sub": [ 176 | "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/POST/", 177 | { 178 | "__Stage__": "Prod", 179 | "__ApiId__": { 180 | "Ref": "ServerlessRestApi" 181 | } 182 | } 183 | ] 184 | } 185 | } 186 | }, 187 | "HelloFunctionRootPermissionTest": { 188 | "Type": "AWS::Lambda::Permission", 189 | "Properties": { 190 | "Action": "lambda:invokeFunction", 191 | "Principal": "apigateway.amazonaws.com", 192 | "FunctionName": { 193 | "Ref": "HelloFunction" 194 | }, 195 | "SourceArn": { 196 | "Fn::Sub": [ 197 | "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/GET/", 198 | { 199 | "__Stage__": "*", 200 | "__ApiId__": { 201 | "Ref": "ServerlessRestApi" 202 | } 203 | } 204 | ] 205 | } 206 | } 207 | }, 208 | "HelloFunctionVersionPermissionTest": { 209 | "Type": "AWS::Lambda::Permission", 210 | "Properties": { 211 | "Action": "lambda:invokeFunction", 212 | "Principal": "apigateway.amazonaws.com", 213 | "FunctionName": { 214 | "Ref": "HelloFunction" 215 | }, 216 | "SourceArn": { 217 | "Fn::Sub": [ 218 | "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/GET/version", 219 | { 220 | "__Stage__": "*", 221 | "__ApiId__": { 222 | "Ref": "ServerlessRestApi" 223 | } 224 | } 225 | ] 226 | } 227 | } 228 | }, 229 | "ServerlessRestApi": { 230 | "Type": "AWS::ApiGateway::RestApi", 231 | "Properties": { 232 | "Body": { 233 | "info": { 234 | "version": "1.0", 235 | "title": { 236 | "Ref": "AWS::StackName" 237 | } 238 | }, 239 | "paths": { 240 | "/version": { 241 | "get": { 242 | "x-amazon-apigateway-integration": { 243 | "httpMethod": "POST", 244 | "type": "aws_proxy", 245 | "uri": { 246 | "Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HelloFunction.Arn}/invocations" 247 | } 248 | }, 249 | "responses": {} 250 | } 251 | }, 252 | "/": { 253 | "post": { 254 | "x-amazon-apigateway-integration": { 255 | "httpMethod": "POST", 256 | "type": "aws_proxy", 257 | "uri": { 258 | "Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HelloFunction.Arn}/invocations" 259 | } 260 | }, 261 | "responses": {} 262 | }, 263 | "get": { 264 | "x-amazon-apigateway-integration": { 265 | "httpMethod": "POST", 266 | "type": "aws_proxy", 267 | "uri": { 268 | "Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HelloFunction.Arn}/invocations" 269 | } 270 | }, 271 | "responses": {} 272 | } 273 | } 274 | }, 275 | "swagger": "2.0" 276 | } 277 | } 278 | } 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /aws.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "fmt" 7 | "html/template" 8 | "os" 9 | "strings" 10 | "text/tabwriter" 11 | "time" 12 | 13 | "github.com/aws/aws-sdk-go-v2/aws/external" 14 | "github.com/aws/aws-sdk-go/aws" 15 | "github.com/aws/aws-sdk-go/aws/session" 16 | "github.com/aws/aws-sdk-go/service/ec2" 17 | ) 18 | 19 | const msgTemplate = `{ "text": "Instances", 20 | "attachments": [ 21 | {{ range . }} 22 | {{ range .Instances }} 23 | { "title" : "{{- range .Tags }} 24 | {{- if eq ( Deref .Key ) "Name" }} 25 | {{- .Value}} 26 | {{- end}} 27 | {{- end}}", 28 | 29 | 30 | "footer": "{{ .LaunchTime }}", 31 | {{ if eq "running" (Deref .State.Name) }} "color":"#36a64f" ,{{end}} 32 | "fields": [ 33 | { 34 | "title": "PublicIP", 35 | "value": "{{ .PublicIpAddress}}", 36 | "short": true 37 | }, 38 | { 39 | "title": "Zone", 40 | "value": "{{ .Placement.AvailabilityZone}}", 41 | "short": true 42 | }, 43 | { 44 | "title": "State", 45 | "value": "{{ .State.Name }}", 46 | "short": true 47 | }, 48 | { 49 | "title": "InstanceId", 50 | "value": "{{ .InstanceId}}", 51 | "short": true 52 | } 53 | ] 54 | }, 55 | {{end}} 56 | {{end}} 57 | ] 58 | }` 59 | const asciiTemplate = `{ "text": " instances: ` + "```" + ` 60 | -------------------------------------------------------------------------------------------------------------+ 61 | {{ printf "%-20s" "instanceId" }} | 62 | {{- printf " %-32s" "name" }} | 63 | {{- printf " %-16s" "publicIp" }} | 64 | {{- printf " %-12s" "region" }} | 65 | {{- printf " %-16s" "started" }} | 66 | -------------------------------------------------------------------------------------------------------------+ 67 | {{ range . }} 68 | {{- range .Instances }} 69 | {{- .InstanceId | Deref | printf "%-20s" }} | 70 | {{- range .Tags }} 71 | {{- if eq ( Deref .Key ) "Name" }} 72 | {{- .Value | Deref | printf " %-32s"}} 73 | {{- end}} 74 | {{- end}} | 75 | {{- .PublicIpAddress | Deref | printf " %-16s" }} | 76 | {{- .Placement.AvailabilityZone | Deref | printf " %-12s" }} | 77 | {{- .LaunchTime | Hours | printf "%-16s"}} | 78 | {{ end}} 79 | {{- end}}-------------------------------------------------------------------------------------------------------------+` + 80 | "```" + `"}` 81 | 82 | const asciiTemplateHours = `{ "text": " instances: ` + "```" + ` 83 | ----------------------------------------------------------------------------------------------------------------+ 84 | {{ printf "%-20s" "instanceId" }} | 85 | {{- printf " %-30s" "name" }} | 86 | {{- printf " %-14s" "publicIp" }} | 87 | {{- printf " %-12s" "region" }} | 88 | {{- printf " %-5s" "hours" }} | 89 | {{- printf " %-9s" "insType" }} | 90 | {{- printf " %-3s" "spt" }} | 91 | ----------------------------------------------------------------------------------------------------------------+ 92 | {{ range . }} 93 | {{- range .Instances }} 94 | {{- .InstanceId | Deref | printf "%-20s" }} | 95 | {{- if .Tags}}{{- range .Tags }} 96 | {{- if eq ( Deref .Key ) "Name" }} 97 | {{- .Value | Deref | printf " %-30s"}} 98 | {{- end}} 99 | {{- end}}{{- else}}{{"NONAME"| printf " %-30s"}}{{end}} | 100 | {{- .PublicIpAddress | Deref | printf " %-14s" }} | 101 | {{- .Placement.AvailabilityZone | Deref | printf " %-12s" }} | 102 | {{- .LaunchTime | Hours | printf "%5sh" }} | 103 | {{- .InstanceType | Deref| printf " %-9s"}} | 104 | {{- if .InstanceLifecycle }} X {{else}} {{end}} | 105 | {{ end}} 106 | {{- end}}----------------------------------------------------------------------------------------------------------------+` + 107 | "```" + `"}` 108 | 109 | const tabwriterTemplate = ` 110 | {{- printf "%s\t%s\t%s\t%s\t%s\t%s\t" "instanceId" "name" "publicIpAddress" "zone" "type" "started"}} 111 | {{ range . }} 112 | {{- range .Instances }} 113 | {{- .InstanceId | Deref }}{{"\t"}} 114 | {{- . | Tag "Name" }}{{"\t"}} 115 | {{- .PublicIpAddress | Deref }}{{"\t"}} 116 | {{- .Placement.AvailabilityZone | Deref }}{{"\t"}} 117 | {{- .InstanceType | Deref }}{{"\t"}} 118 | {{- .LaunchTime | Hours }}h{{"\t"}} 119 | {{- end}} 120 | {{ end}} 121 | ` 122 | 123 | func formatInstances(reservations []*ec2.Reservation, toAscii bool) string { 124 | actualTempl := msgTemplate 125 | if toAscii { 126 | //actualTempl = asciiTemplateHours 127 | actualTempl = tabwriterTemplate 128 | } 129 | tmpl, err := template.New("test").Funcs(template.FuncMap{ 130 | "Deref": aws.StringValue, 131 | "Tag": func(keyname string, ins *ec2.Instance) string { 132 | for _, t := range ins.Tags { 133 | if aws.StringValue(t.Key) == keyname { 134 | return aws.StringValue(t.Value) 135 | } 136 | } 137 | return "n/a" 138 | }, 139 | "Hours": func(t *time.Time) string { 140 | return strings.Split(fmt.Sprint(time.Since(*t).Truncate(time.Hour)), "h")[0] 141 | }, 142 | }).Parse(actualTempl) 143 | 144 | if err != nil { 145 | panic(err) 146 | } 147 | 148 | var b bytes.Buffer 149 | var output bytes.Buffer 150 | w := tabwriter.NewWriter(&b, 0, 0, 1, ' ', tabwriter.Debug) 151 | err = tmpl.Execute(w, reservations) 152 | if err != nil { 153 | panic(err) 154 | } 155 | w.Flush() 156 | 157 | scan := bufio.NewScanner(&b) 158 | scan.Scan() 159 | firstLine := scan.Text() 160 | fmt.Fprintln(&output, firstLine) 161 | fmt.Fprintln(&output, strings.Repeat("-", len(firstLine))) 162 | for scan.Scan() { 163 | fmt.Fprintln(&output, scan.Text()) 164 | } 165 | 166 | return output.String() 167 | 168 | } 169 | 170 | func awsInstancesInRegion(reg string) []*ec2.Reservation { 171 | 172 | fmt.Println("query reg:", reg, "started ...") 173 | sess := session.Must(session.NewSession(&aws.Config{ 174 | Region: aws.String(reg), 175 | })) 176 | svc := ec2.New(sess) 177 | din, err := svc.DescribeInstances(&ec2.DescribeInstancesInput{ 178 | Filters: []*ec2.Filter{ 179 | &ec2.Filter{ 180 | Name: aws.String("instance-state-name"), 181 | Values: aws.StringSlice([]string{"running"}), 182 | }, 183 | }, 184 | }) 185 | if err != nil { 186 | panic(err) 187 | } 188 | return din.Reservations 189 | } 190 | 191 | func awsInsatncesMsg(respUrl string, toAscii bool) string { 192 | 193 | _, err := external.LoadDefaultAWSConfig() 194 | if err != nil { 195 | panic(err) 196 | } 197 | 198 | if os.Getenv("regions") == "" { 199 | os.Setenv("regions", "eu-west-1,eu-central-1,us-east-1") 200 | } 201 | regions := strings.Split(os.Getenv("regions"), ",") 202 | chIns := make(chan []*ec2.Reservation, len(regions)) 203 | 204 | for _, r := range regions { 205 | go func(reg string) { 206 | chIns <- awsInstancesInRegion(reg) 207 | }(r) 208 | } 209 | 210 | allInstances := make([]*ec2.Reservation, 0) 211 | for range regions { 212 | allInstances = append(allInstances, <-chIns...) 213 | } 214 | 215 | msg := formatInstances(allInstances, toAscii) 216 | 217 | //saveAwsResponse(allInstances) 218 | 219 | /* simple plain text respnse, insread of delayed answer on response_url 220 | slackMsg := `{ "text": " instances: ` + "```" + msg + "```" + `"}` 221 | resp, err := http.Post(respUrl, "application/json", bytes.NewBufferString(slackMsg)) 222 | if err != nil { 223 | panic(err) 224 | } 225 | log.Println("slack resp:", resp.Status) 226 | */ 227 | return "```" + msg + "```" 228 | 229 | } 230 | -------------------------------------------------------------------------------- /aws_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/gob" 5 | "fmt" 6 | "os" 7 | 8 | "github.com/aws/aws-sdk-go/service/ec2" 9 | ) 10 | 11 | func saveAwsResponse(allInstances []*ec2.Reservation) { 12 | f, err := os.Create("insatnces.gob") 13 | if err != nil { 14 | panic(err) 15 | } 16 | 17 | enc := gob.NewEncoder(f) 18 | err = enc.Encode(allInstances) 19 | if err != nil { 20 | panic(err) 21 | } 22 | } 23 | 24 | func read() { 25 | f, err := os.Open("insatnces.gob") 26 | if err != nil { 27 | panic(err) 28 | } 29 | dec := gob.NewDecoder(f) 30 | var reservations []*ec2.Reservation 31 | dec.Decode(&reservations) 32 | 33 | /* 34 | tmpl, err := template.New("test").Funcs(template.FuncMap{ 35 | "Deref": aws.StringValue, 36 | "Tag": func(keyname string, ins *ec2.Instance) string { 37 | for _, t := range ins.Tags { 38 | if aws.StringValue(t.Key) == keyname { 39 | return aws.StringValue(t.Value) 40 | } 41 | } 42 | return "n/a" 43 | }, 44 | "Hours": func(t *time.Time) string { 45 | return strings.Split(fmt.Sprint(time.Since(*t).Truncate(time.Hour)), "h")[0] 46 | }, 47 | }).Parse(tabwriterTemplate) 48 | if err != nil { 49 | panic(err) 50 | } 51 | 52 | var b bytes.Buffer 53 | w := tabwriter.NewWriter(&b, 0, 0, 1, ' ', tabwriter.Debug) 54 | tmpl.Execute(w, reservations) 55 | w.Flush() 56 | 57 | scan := bufio.NewScanner(&b) 58 | scan.Scan() 59 | firstLine := scan.Text() 60 | fmt.Println(firstLine) 61 | fmt.Println(strings.Repeat("-", len(firstLine))) 62 | for scan.Scan() { 63 | fmt.Println(scan.Text()) 64 | } 65 | */ 66 | 67 | fmt.Printf("FORMATTED:\n%s\n", formatInstances(reservations, true)) 68 | } 69 | -------------------------------------------------------------------------------- /cmds/aws.bash: -------------------------------------------------------------------------------- 1 | init() { 2 | cmd-export-ns aws "aws namespace" 3 | cmd-export aws-logstreams 4 | cmd-export aws-logs 5 | cmd-export aws-listStacks 6 | cmd-export aws-price 7 | 8 | #AWS=$(which aws) 9 | deps-require aws 10 | AWS=.gun/bin/aws 11 | } 12 | aws-loggroups() { 13 | declare desc="lists aws loggroups" 14 | declare groupPattern=${1} 15 | 16 | $AWS logs describe-log-groups \ 17 | --query 'logGroups[?contains(logGroupName,`'${groupPattern}'`)].logGroupName' \ 18 | --out text 19 | } 20 | 21 | aws-logstreams() { 22 | declare desc="lists log streams belonging to a log group pattern" 23 | declare groupPattern=${1:? groupPattern required} 24 | 25 | groupName=$(aws-loggroups $groupPattern) 26 | $AWS logs describe-log-streams \ 27 | --log-group-name $groupName \ 28 | --query 'logStreams[-1].logStreamName' \ 29 | --out text 30 | } 31 | 32 | aws-logs() { 33 | declare desc="list log messages belonging to a log group pattern" 34 | declare groupPattern=${1:? groupPattern required} 35 | declare messagePattern=${2} 36 | 37 | groupName=$(aws-loggroups $groupPattern) 38 | streamName=$(aws-logstreams $groupName) 39 | $AWS logs filter-log-events \ 40 | --log-group-name $groupName \ 41 | --log-stream-names $streamName \ 42 | --query 'events[?contains(message,`'$messagePattern'`)].message' \ 43 | --out text 44 | } 45 | 46 | aws-listStacks() { 47 | declare desc="List cloudformation stacks with CREATE_XXX state" 48 | 49 | $AWS cloudformation list-stacks \ 50 | --query 'StackSummaries[?contains([`CREATE_COMPLETE`,`CREATE_IN_PROGRESS`,`UPDATE_COMPLETE`,`UPDATE_IN_PROGRESS`], 51 | StackStatus)].StackName' \ 52 | --out table 53 | } 54 | 55 | aws-price() { 56 | declare desc="Get instance price" 57 | declare instanceType=$1 region=$2 58 | 59 | : ${instanceType:? required} ${region:? required} 60 | 61 | $AWS pricing get-products \ 62 | --service-code AmazonEC2 \ 63 | --region us-east-1 \ 64 | --filters \ 65 | Type=TERM_MATCH,Field=instanceType,Value=${instanceType} \ 66 | Type=TERM_MATCH,Field=location,Value="EU (Ireland)" \ 67 | Type=TERM_MATCH,Field=operatingSystem,Value=Linux \ 68 | Type=TERM_MATCH,Field=tenancy,Value=Shared \ 69 | Type=TERM_MATCH,Field=preInstalledSw,Value=NA \ 70 | Type=TERM_MATCH,Field=operation,Value=RunInstances \ 71 | --query 'PriceList[]' --out text \ 72 | | jq -r '.terms.OnDemand|..|.pricePerUnit?| select(.)|.USD' 73 | } 74 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strings" 9 | 10 | "github.com/aws/aws-lambda-go/events" 11 | "github.com/aws/aws-lambda-go/lambda" 12 | ) 13 | 14 | var ( 15 | // ErrNameNotProvided is thrown when a name is not provided 16 | ErrNameNotProvided = errors.New("no name was provided in the HTTP body") 17 | ) 18 | 19 | const DEFAULT_RESPONSE string = "done" 20 | 21 | var Version = "" 22 | 23 | // Handler is your Lambda function handler 24 | // It uses Amazon API Gateway request/responses provided by the aws-lambda-go/events package, 25 | // However you could use other event sources (S3, Kinesis etc), or JSON-decoded primitive types such as 'string'. 26 | func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { 27 | log.Println("ENV", os.Environ()) 28 | 29 | // stdout and stderr are sent to AWS CloudWatch Logs 30 | log.Printf("[v0.4] Processing Lambda request %s\n", request.RequestContext.RequestID) 31 | 32 | log.Println("method:", request.HTTPMethod, "path:", request.Path, "res:", request.Resource) 33 | 34 | if request.HTTPMethod == "GET" { 35 | 36 | return events.APIGatewayProxyResponse{ 37 | Body: fmt.Sprintf("version: %v", Version), 38 | StatusCode: 200, 39 | }, nil 40 | } 41 | // If no name is provided in the HTTP request body, throw an error 42 | if len(request.Body) < 1 { 43 | return events.APIGatewayProxyResponse{}, ErrNameNotProvided 44 | } 45 | 46 | log.Printf("[v0.4] BODY: %s\n", request.Body) 47 | 48 | /* 49 | m, err := url.ParseQuery(request.Body) 50 | if err != nil { 51 | panic(err) 52 | } 53 | resp := m["response_url"][0] 54 | command := m["command"][0] 55 | text := m["text"][0] 56 | log.Println("response_url", resp, "command:", command, "text:", text) 57 | */ 58 | 59 | msg := awsInsatncesMsg("", true) 60 | return events.APIGatewayProxyResponse{ 61 | Body: msg, 62 | StatusCode: 200, 63 | }, nil 64 | 65 | } 66 | 67 | func main() { 68 | if os.Getenv("LAMBDA_RUNTIME_DIR") != "" { 69 | lambda.Start(Handler) 70 | } else { 71 | if len(os.Args) > 1 && strings.Contains(os.Args[1], "version") { 72 | fmt.Println("version:", Version) 73 | } else { 74 | fmt.Println(awsInsatncesMsg("", true)) 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main_test 2 | 3 | import ( 4 | "testing" 5 | 6 | main "github.com/lalyos/lambdatest" 7 | 8 | "github.com/aws/aws-lambda-go/events" 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func TestHandler(t *testing.T) { 13 | 14 | tests := []struct { 15 | request events.APIGatewayProxyRequest 16 | expect string 17 | err error 18 | }{ 19 | { 20 | // Test that the handler responds with the correct response 21 | // when a valid name is provided in the HTTP body 22 | request: events.APIGatewayProxyRequest{Body: "Paul"}, 23 | expect: "mingya mingya ...", 24 | err: nil, 25 | }, 26 | { 27 | // Test that the handler responds ErrNameNotProvided 28 | // when no name is provided in the HTTP body 29 | request: events.APIGatewayProxyRequest{Body: ""}, 30 | expect: "", 31 | err: main.ErrNameNotProvided, 32 | }, 33 | } 34 | 35 | for _, test := range tests { 36 | response, err := main.Handler(test.request) 37 | assert.IsType(t, test.err, err) 38 | assert.Equal(t, test.expect, response.Body) 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /template.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Transform: AWS::Serverless-2016-10-31 3 | 4 | Resources: 5 | HelloFunction: 6 | Type: AWS::Serverless::Function 7 | Properties: 8 | Handler: main 9 | Runtime: go1.x 10 | Environment: 11 | Variables: 12 | REGIONS: eu-west-1,eu-west-2,eu-west-3,eu-central-1,us-east-1,us-east-2,us-west-1,us-west-2 13 | Policies: AmazonEC2ReadOnlyAccess 14 | Events: 15 | SlackPost: 16 | Type: Api 17 | Properties: 18 | Path: / 19 | Method: post 20 | Root: 21 | Type: Api 22 | Properties: 23 | Path: / 24 | Method: get 25 | Version: 26 | Type: Api 27 | Properties: 28 | Path: /version 29 | Method: get 30 | Outputs: 31 | RestUrl: 32 | Description: External Rest Api url 33 | Value: !Join [ "", [ "https://", !Ref ServerlessRestApi , ".execute-api.", !Ref "AWS::Region" , ".amazonaws.com/", !Ref ServerlessRestApiProdStage ] ] 34 | --------------------------------------------------------------------------------