├── LICENSE ├── README.md ├── portal ├── Dockerfile ├── Gemfile ├── Gemfile.lock ├── portal.rb └── public │ └── index.html ├── service-discovery-blog-template ├── stock-price ├── Dockerfile ├── Gemfile ├── Gemfile.lock └── stocks.rb └── weather ├── Dockerfile ├── Gemfile ├── Gemfile.lock └── weather.rb /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 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # service-discovery-ecs-consul 2 | This repository provides the assets referred to in the blog post [Service Discovery via Consul with Amazon ECS] (https://aws.amazon.com/blogs/compute/service-discovery-via-consul-with-amazon-ecs/). Service discovery tools manage how processes and services in a cluster can find and talk to one another. The post demonstrates how a tool called Consul can augment the capabilities of Amazon ECS by providing service discovery for an ECS cluster. 3 | -------------------------------------------------------------------------------- /portal/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ruby:2.1-onbuild 2 | EXPOSE 4567 3 | 4 | RUN chmod u+x ./portal.rb 5 | 6 | CMD ["./portal.rb"] 7 | -------------------------------------------------------------------------------- /portal/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | gem 'sinatra' 3 | -------------------------------------------------------------------------------- /portal/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | mustermann (1.1.1) 5 | ruby2_keywords (~> 0.0.1) 6 | rack (2.2.3) 7 | rack-protection (2.0.8.1) 8 | rack 9 | ruby2_keywords (0.0.2) 10 | sinatra (2.0.8.1) 11 | mustermann (~> 1.0) 12 | rack (~> 2.0) 13 | rack-protection (= 2.0.8.1) 14 | tilt (~> 2.0) 15 | tilt (2.0.10) 16 | 17 | PLATFORMS 18 | ruby 19 | 20 | DEPENDENCIES 21 | sinatra 22 | 23 | BUNDLED WITH 24 | 2.1.4 25 | -------------------------------------------------------------------------------- /portal/portal.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'sinatra' 3 | require 'net/http' 4 | require 'json' 5 | require 'resolv' 6 | 7 | set :bind, '0.0.0.0' 8 | 9 | # The main web page. 10 | get '/' do 11 | redirect '/index.html' 12 | end 13 | 14 | # The URI to do a temperature lookup for the specified city. 15 | # Returns a JSON document with city name, country and temperature. 16 | get '/weather/:city' do 17 | lookup_weather(params['city']) 18 | end 19 | 20 | # The URI to do the stock symbol lookup. 21 | # Returns a JSON document with stock name and price. 22 | get '/stock/:symbol' do 23 | lookup_stock(params['symbol']) 24 | end 25 | 26 | # The URI for the health check 27 | get '/health' do 28 | "OK" 29 | end 30 | 31 | # The function to lookup weather for a particular city. 32 | # Looks up the weather microservice and returns JSON doc 33 | def lookup_weather(city) 34 | address, port = lookup_service('weather') 35 | uri = URI.parse(URI.encode("http://#{address}:#{port}/weather/#{city}")) 36 | res = Net::HTTP.get_response(uri) 37 | res.body if res.is_a?(Net::HTTPSuccess) 38 | end 39 | 40 | # The function to lookup stock price for a particular symbol. 41 | # Looks up the 'stock-price' microservice and returns JSON doc 42 | def lookup_stock(stock) 43 | address, port = lookup_service('stock-price') 44 | uri = URI.parse(URI.encode("http://#{address}:#{port}/stock/#{stock}")) 45 | res = Net::HTTP.get_response(uri) 46 | res.body if res.is_a?(Net::HTTPSuccess) 47 | end 48 | 49 | # Function to return an IP address and port number for a given service name 50 | # Assumes Consul agent is running locally and acting as the default DNS resolver 51 | def lookup_service(service_name) 52 | resolver = Resolv::DNS.open 53 | record = resolver.getresource(service_name, Resolv::DNS::Resource::IN::SRV) 54 | return resolver.getaddress(record.target), record.port 55 | end 56 | -------------------------------------------------------------------------------- /portal/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 86 | 87 | 88 | Consul client lookup demo 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 |

Stocks

98 |
99 | 100 |
101 | Add stock: 102 | 103 | 104 |
105 | 106 |
107 | 108 | 111 | 112 | 115 | 116 | 119 | 120 | Powered by the Yahoo Finance API 121 | 122 |
123 | 124 |

Weather

125 |
126 | 127 |
128 | Add city: 129 | 130 | 131 |
132 | 133 |
134 | 135 | 138 | 139 | 142 | 143 | 144 | 147 | 148 | Powered by the Open Weather Map API 149 | 150 |
151 | 152 | 153 | 154 | 251 | 252 | -------------------------------------------------------------------------------- /service-discovery-blog-template: -------------------------------------------------------------------------------- 1 | { 2 | "AWSTemplateFormatVersion": "2010-09-09", 3 | "Description": "AWS CloudFormation template to create an IAM role, Security Groups, Consul Server and cluster of Consul agents in an ECS Cluster. Please note that this is not designed for production usage.", 4 | "Mappings": { 5 | "ConsulServerAmiMap": { 6 | "eu-west-1": { 7 | "AMI": "ami-a10897d6" 8 | }, 9 | "us-east-1": { 10 | "AMI": "ami-1ecae776" 11 | }, 12 | "us-west-2": { 13 | "AMI": "ami-e7527ed7" 14 | } 15 | }, 16 | "EcsNodeAmiMap": { 17 | "eu-west-1": { 18 | "AMI": "ami-ed7c149a" 19 | }, 20 | "us-east-1": { 21 | "AMI": "ami-d0b9acb8" 22 | }, 23 | "us-west-2": { 24 | "AMI": "ami-6b88b95b" 25 | } 26 | }, 27 | "DcMap": { 28 | "eu-west-1": { 29 | "Value": "eu1" 30 | }, 31 | "us-east-1": { 32 | "Value": "us1" 33 | }, 34 | "us-west-2": { 35 | "Value": "us2" 36 | } 37 | } 38 | }, 39 | "Parameters": { 40 | "EcsInstanceType": { 41 | "Type": "String", 42 | "Description": "ECS instance type", 43 | "Default": "t2.micro", 44 | "AllowedValues": [ 45 | "t2.micro", 46 | "t2.small", 47 | "t2.medium", 48 | "m3.medium", 49 | "m3.large", 50 | "m3.xlarge", 51 | "m3.2xlarge", 52 | "c4.large", 53 | "c4.xlarge", 54 | "c4.2xlarge", 55 | "c4.4xlarge", 56 | "c4.8xlarge", 57 | "c3.large", 58 | "c3.xlarge", 59 | "c3.2xlarge", 60 | "c3.4xlarge", 61 | "c3.8xlarge", 62 | "r3.large", 63 | "r3.xlarge", 64 | "r3.2xlarge", 65 | "r3.4xlarge", 66 | "r3.8xlarge", 67 | "i2.xlarge", 68 | "i2.2xlarge", 69 | "i2.4xlarge", 70 | "i2.8xlarge" 71 | ], 72 | "ConstraintDescription": "must be a valid EC2 instance type." 73 | }, 74 | "ServerInstanceType": { 75 | "Type": "String", 76 | "Description": "Consul Server EC2 instance type", 77 | "Default": "t2.micro", 78 | "AllowedValues": [ 79 | "t2.micro", 80 | "t2.small", 81 | "t2.medium", 82 | "m3.medium", 83 | "m3.large", 84 | "m3.xlarge", 85 | "m3.2xlarge", 86 | "c4.large", 87 | "c4.xlarge", 88 | "c4.2xlarge", 89 | "c4.4xlarge", 90 | "c4.8xlarge", 91 | "c3.large", 92 | "c3.xlarge", 93 | "c3.2xlarge", 94 | "c3.4xlarge", 95 | "c3.8xlarge", 96 | "r3.large", 97 | "r3.xlarge", 98 | "r3.2xlarge", 99 | "r3.4xlarge", 100 | "r3.8xlarge", 101 | "i2.xlarge", 102 | "i2.2xlarge", 103 | "i2.4xlarge", 104 | "i2.8xlarge" 105 | ], 106 | "ConstraintDescription": "must be a valid EC2 instance type." 107 | }, 108 | "KeyName": { 109 | "Type": "AWS::EC2::KeyPair::KeyName", 110 | "Description": "Name of an existing EC2 KeyPair to enable SSH access to the EC2 instances" 111 | }, 112 | "ClusterSize": { 113 | "Type": "Number", 114 | "Description": "Expected size of the ECS cluster", 115 | "Default": "1" 116 | }, 117 | "EcsClusterName": { 118 | "Type": "String", 119 | "Description": "ECS Cluster Name", 120 | "Default": "default" 121 | }, 122 | "SourceCidr": { 123 | "Type": "String", 124 | "Description": "Optional - CIDR/IP range for ECS instance outside access - defaults to 0.0.0.0/0", 125 | "Default": "0.0.0.0/0" 126 | }, 127 | "VPC": { 128 | "Type": "AWS::EC2::VPC::Id", 129 | "Description": "The VPC Id where the instances will be deployed into." 130 | }, 131 | "SubnetId": { 132 | "Type": "AWS::EC2::Subnet::Id", 133 | "Description": "The Subnet Id where the instances will be deployed into. Must be a subnet in the the same VPC as the VPC Id input parameter." 134 | }, 135 | "AZ": { 136 | "Type": "AWS::EC2::AvailabilityZone::Name", 137 | "Description": "The Availability Zone of the Subnet. Must be the same Availabile Zone as the SubnetId parameter." 138 | }, 139 | "AmazonDnsIp": { 140 | "Type": "String", 141 | "Description": "The IP address of the VPC DNS service running on a reserved IP address at the base of the VPC network range \"plus two\". ", 142 | "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})", 143 | "Default": "10.0.0.2" 144 | }, 145 | "HttpPassword": { 146 | "Type": "String", 147 | "NoEcho": "true", 148 | "Description": "The HTTP password for access to the Consul GUI", 149 | "AllowedPattern": "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})", 150 | "ConstraintDescription": "Entry that must contains one digit from 0-9, one lowercase characters, one uppercase characters, one special symbols in the list \"@#$%\" and between 6 and 20 characters in length." 151 | } 152 | }, 153 | "Resources": { 154 | "ConsulAgentSecurityGroup": { 155 | "Type": "AWS::EC2::SecurityGroup", 156 | "Properties": { 157 | "GroupDescription": "Consul Agent Security Group", 158 | "VpcId": { 159 | "Ref": "VPC" 160 | }, 161 | "Tags": [ 162 | { 163 | "Key": "Name", 164 | "Value": "ConsulAgentSG" 165 | } 166 | ] 167 | } 168 | }, 169 | "ConsulServerSecurityGroup": { 170 | "Type": "AWS::EC2::SecurityGroup", 171 | "Properties": { 172 | "GroupDescription": "Consul Server Security Group", 173 | "VpcId": { 174 | "Ref": "VPC" 175 | }, 176 | "SecurityGroupIngress": [ 177 | { 178 | "IpProtocol": "tcp", 179 | "FromPort": "8300", 180 | "ToPort": "8300", 181 | "SourceSecurityGroupId": { 182 | "Ref": "ConsulAgentSecurityGroup" 183 | } 184 | } 185 | ], 186 | "Tags": [ 187 | { 188 | "Key": "Name", 189 | "Value": "ConsulServerSG" 190 | } 191 | ] 192 | } 193 | }, 194 | "ConsulAgentSecurityGroupIngressTcpEphemeral": { 195 | "DependsOn": [ 196 | "ConsulAgentSecurityGroup" 197 | ], 198 | "Type": "AWS::EC2::SecurityGroupIngress", 199 | "Properties": { 200 | "GroupId": { 201 | "Ref": "ConsulAgentSecurityGroup" 202 | }, 203 | "IpProtocol": "tcp", 204 | "FromPort": "32768", 205 | "ToPort": "65535", 206 | "SourceSecurityGroupId": { 207 | "Ref": "ConsulAgentSecurityGroup" 208 | } 209 | } 210 | }, 211 | "ConsulAgentSecurityGroupIngressUdpEphemeral": { 212 | "DependsOn": [ 213 | "ConsulAgentSecurityGroup" 214 | ], 215 | "Type": "AWS::EC2::SecurityGroupIngress", 216 | "Properties": { 217 | "GroupId": { 218 | "Ref": "ConsulAgentSecurityGroup" 219 | }, 220 | "IpProtocol": "udp", 221 | "FromPort": "32768", 222 | "ToPort": "65535", 223 | "SourceSecurityGroupId": { 224 | "Ref": "ConsulAgentSecurityGroup" 225 | } 226 | } 227 | }, 228 | "ConsulAgentSecurityGroupIngressDnsUdp": { 229 | "DependsOn": [ 230 | "ConsulAgentSecurityGroup" 231 | ], 232 | "Type": "AWS::EC2::SecurityGroupIngress", 233 | "Properties": { 234 | "GroupId": { 235 | "Ref": "ConsulAgentSecurityGroup" 236 | }, 237 | "IpProtocol": "udp", 238 | "FromPort": "8600", 239 | "ToPort": "8600", 240 | "SourceSecurityGroupId": { 241 | "Ref": "ConsulAgentSecurityGroup" 242 | } 243 | } 244 | }, 245 | "ConsulAgentSecurityGroupIngressDnsTcp": { 246 | "DependsOn": [ 247 | "ConsulAgentSecurityGroup" 248 | ], 249 | "Type": "AWS::EC2::SecurityGroupIngress", 250 | "Properties": { 251 | "GroupId": { 252 | "Ref": "ConsulAgentSecurityGroup" 253 | }, 254 | "IpProtocol": "tcp", 255 | "FromPort": "8600", 256 | "ToPort": "8600", 257 | "SourceSecurityGroupId": { 258 | "Ref": "ConsulAgentSecurityGroup" 259 | } 260 | } 261 | }, 262 | "ConsulAgentSecurityGroupIngressHttp": { 263 | "DependsOn": [ 264 | "ConsulAgentSecurityGroup" 265 | ], 266 | "Type": "AWS::EC2::SecurityGroupIngress", 267 | "Properties": { 268 | "GroupId": { 269 | "Ref": "ConsulAgentSecurityGroup" 270 | }, 271 | "IpProtocol": "tcp", 272 | "FromPort": "8500", 273 | "ToPort": "8500", 274 | "SourceSecurityGroupId": { 275 | "Ref": "ConsulAgentSecurityGroup" 276 | } 277 | } 278 | }, 279 | "ConsulAgentSecurityGroupIngressCli": { 280 | "DependsOn": [ 281 | "ConsulAgentSecurityGroup" 282 | ], 283 | "Type": "AWS::EC2::SecurityGroupIngress", 284 | "Properties": { 285 | "GroupId": { 286 | "Ref": "ConsulAgentSecurityGroup" 287 | }, 288 | "IpProtocol": "tcp", 289 | "FromPort": "8400", 290 | "ToPort": "8400", 291 | "SourceSecurityGroupId": { 292 | "Ref": "ConsulAgentSecurityGroup" 293 | } 294 | } 295 | }, 296 | "ConsulAgentSecurityGroupIngressSerfLanUdp": { 297 | "DependsOn": [ 298 | "ConsulAgentSecurityGroup" 299 | ], 300 | "Type": "AWS::EC2::SecurityGroupIngress", 301 | "Properties": { 302 | "GroupId": { 303 | "Ref": "ConsulAgentSecurityGroup" 304 | }, 305 | "IpProtocol": "udp", 306 | "FromPort": "8301", 307 | "ToPort": "8301", 308 | "SourceSecurityGroupId": { 309 | "Ref": "ConsulAgentSecurityGroup" 310 | } 311 | } 312 | }, 313 | "ConsulAgentSecurityGroupIngressSerfLanTcp": { 314 | "DependsOn": [ 315 | "ConsulAgentSecurityGroup" 316 | ], 317 | "Type": "AWS::EC2::SecurityGroupIngress", 318 | "Properties": { 319 | "GroupId": { 320 | "Ref": "ConsulAgentSecurityGroup" 321 | }, 322 | "IpProtocol": "tcp", 323 | "FromPort": "8301", 324 | "ToPort": "8301", 325 | "SourceSecurityGroupId": { 326 | "Ref": "ConsulAgentSecurityGroup" 327 | } 328 | } 329 | }, 330 | "ConsulServerSecurityGroupIngressSerfWanTcp": { 331 | "DependsOn": [ 332 | "ConsulServerSecurityGroup" 333 | ], 334 | "Type": "AWS::EC2::SecurityGroupIngress", 335 | "Properties": { 336 | "GroupId": { 337 | "Ref": "ConsulServerSecurityGroup" 338 | }, 339 | "IpProtocol": "tcp", 340 | "FromPort": "8302", 341 | "ToPort": "8302", 342 | "SourceSecurityGroupId": { 343 | "Ref": "ConsulServerSecurityGroup" 344 | } 345 | } 346 | }, 347 | "ConsulServerSecurityGroupIngressSerfWanUdp": { 348 | "DependsOn": [ 349 | "ConsulServerSecurityGroup" 350 | ], 351 | "Type": "AWS::EC2::SecurityGroupIngress", 352 | "Properties": { 353 | "GroupId": { 354 | "Ref": "ConsulServerSecurityGroup" 355 | }, 356 | "IpProtocol": "udp", 357 | "FromPort": "8302", 358 | "ToPort": "8302", 359 | "SourceSecurityGroupId": { 360 | "Ref": "ConsulServerSecurityGroup" 361 | } 362 | } 363 | }, 364 | "CommonSecurityGroup": { 365 | "Type": "AWS::EC2::SecurityGroup", 366 | "Properties": { 367 | "GroupDescription": "ECS Security Group", 368 | "VpcId": { 369 | "Ref": "VPC" 370 | }, 371 | "SecurityGroupIngress": [ 372 | { 373 | "IpProtocol": "tcp", 374 | "FromPort": "22", 375 | "ToPort": "22", 376 | "CidrIp": { 377 | "Ref": "SourceCidr" 378 | } 379 | }, 380 | { 381 | "IpProtocol": "tcp", 382 | "FromPort": "80", 383 | "ToPort": "80", 384 | "CidrIp": "0.0.0.0/0" 385 | }, 386 | { 387 | "IpProtocol": "tcp", 388 | "FromPort": "443", 389 | "ToPort": "443", 390 | "CidrIp": "0.0.0.0/0" 391 | } 392 | ] 393 | } 394 | }, 395 | "ConsulRole": { 396 | "Type": "AWS::IAM::Role", 397 | "Properties": { 398 | "AssumeRolePolicyDocument": { 399 | "Version": "2012-10-17", 400 | "Statement": [ 401 | { 402 | "Effect": "Allow", 403 | "Principal": { 404 | "Service": [ 405 | "ec2.amazonaws.com" 406 | ] 407 | }, 408 | "Action": [ 409 | "sts:AssumeRole" 410 | ] 411 | } 412 | ] 413 | }, 414 | "Path": "/", 415 | "Policies": [ 416 | { 417 | "PolicyName": "root", 418 | "PolicyDocument": { 419 | "Version": "2012-10-17", 420 | "Statement": [ 421 | { 422 | "Effect": "Allow", 423 | "Action": [ 424 | "ecs:CreateCluster", 425 | "ecs:DeregisterContainerInstance", 426 | "ecs:DiscoverPollEndpoint", 427 | "ecs:Poll", 428 | "ecs:RegisterContainerInstance", 429 | "ecs:Submit*" 430 | ], 431 | "Resource": "*" 432 | }, 433 | { 434 | "Effect": "Allow", 435 | "Action": "ec2:DescribeInstances", 436 | "Resource": "*" 437 | }, 438 | { 439 | "Effect": "Allow", 440 | "Action": [ 441 | "logs:*" 442 | ], 443 | "Resource": [ 444 | "arn:aws:logs:*:*:*" 445 | ] 446 | } 447 | ] 448 | } 449 | } 450 | ] 451 | } 452 | }, 453 | "ConsulInstanceProfile": { 454 | "Type": "AWS::IAM::InstanceProfile", 455 | "Properties": { 456 | "Path": "/", 457 | "Roles": [ 458 | { 459 | "Ref": "ConsulRole" 460 | } 461 | ] 462 | } 463 | }, 464 | "ConsulServer": { 465 | "Type": "AWS::EC2::Instance", 466 | "Metadata": { 467 | "AWS::CloudFormation::Init": { 468 | "configSets": { 469 | "InstallAndRun": [ 470 | "Install", 471 | "Configure", 472 | "StartContainers" 473 | ] 474 | }, 475 | "Install": { 476 | "packages": { 477 | "yum": { 478 | "git": [], 479 | "docker": [], 480 | "nginx": [], 481 | "httpd-devel": [] 482 | } 483 | }, 484 | "files": { 485 | "/etc/nginx/nginx.conf": { 486 | "content": { 487 | "Fn::Join": [ 488 | "\n", 489 | [ 490 | "user nginx;", 491 | "worker_processes 1;", 492 | "error_log /var/log/nginx/error.log;", 493 | "pid /var/run/nginx.pid;", 494 | "events {", 495 | " worker_connections 1024;", 496 | "}", 497 | "", 498 | "http {", 499 | " server {", 500 | " listen 80;", 501 | " location / {", 502 | " proxy_set_header Host $host;", 503 | " proxy_set_header X-Real-IP $remote_addr;", 504 | " proxy_pass http://localhost:8500;", 505 | " auth_basic \"Restricted\";", 506 | " auth_basic_user_file /etc/nginx/.htpasswd;", 507 | " }", 508 | " }", 509 | "}" 510 | ] 511 | ] 512 | }, 513 | "mode": "000755", 514 | "owner": "root", 515 | "group": "root" 516 | } 517 | }, 518 | "services": { 519 | "sysvinit": { 520 | "nginx": { 521 | "enabled": "true", 522 | "ensureRunning": "true", 523 | "files": [ 524 | "/etc/nginx/nginx.conf" 525 | ] 526 | }, 527 | "docker": { 528 | "enabled": "true", 529 | "ensureRunning": "true" 530 | } 531 | } 532 | } 533 | }, 534 | "Configure": { 535 | "commands": { 536 | "01_create_consul_data_dir": { 537 | "command": { 538 | "Fn::Join": [ 539 | "", 540 | [ 541 | "mkdir -p /opt/consul" 542 | ] 543 | ] 544 | } 545 | }, 546 | "02_add_user_to_docker_group": { 547 | "command": { 548 | "Fn::Join": [ 549 | "", 550 | [ 551 | "usermod -a -G docker ec2-user" 552 | ] 553 | ] 554 | } 555 | }, 556 | "03_pull_consul_image": { 557 | "command": { 558 | "Fn::Join": [ 559 | "", 560 | [ 561 | "docker pull progrium/consul" 562 | ] 563 | ] 564 | } 565 | }, 566 | "04_set_nginx_http_password": { 567 | "command": { 568 | "Fn::Join": [ 569 | " ", 570 | [ 571 | "htpasswd -cb /etc/nginx/.htpasswd admin", 572 | { 573 | "Ref": "HttpPassword" 574 | } 575 | ] 576 | ] 577 | } 578 | }, 579 | "05_reload_nginx": { 580 | "command": { 581 | "Fn::Join": [ 582 | "", 583 | [ 584 | "/usr/sbin/nginx -s reload" 585 | ] 586 | ] 587 | } 588 | } 589 | } 590 | }, 591 | "StartContainers": { 592 | "commands": { 593 | "01_start_consul_docker_container": { 594 | "command": { 595 | "Fn::Join": [ 596 | " ", 597 | [ 598 | "docker run -d --restart=always -p 8300:8300 -p 8301:8301 -p 8301:8301/udp", 599 | "-p 8302:8302 -p 8302:8302/udp -p 8400:8400 -p 8500:8500 -p 53:53/udp", 600 | "-v /opt/consul:/data", 601 | "-h $(curl -s http://169.254.169.254/latest/meta-data/instance-id)", 602 | "--name consul-server progrium/consul -server -bootstrap", 603 | "-dc", 604 | { 605 | "Fn::FindInMap": [ 606 | "DcMap", 607 | { 608 | "Ref": "AWS::Region" 609 | }, 610 | "Value" 611 | ] 612 | }, 613 | "-advertise $(curl -s http://169.254.169.254/latest/meta-data/local-ipv4)", 614 | "-ui-dir /ui" 615 | ] 616 | ] 617 | } 618 | } 619 | } 620 | } 621 | } 622 | }, 623 | "Properties": { 624 | "ImageId": { 625 | "Fn::FindInMap": [ 626 | "ConsulServerAmiMap", 627 | { 628 | "Ref": "AWS::Region" 629 | }, 630 | "AMI" 631 | ] 632 | }, 633 | "InstanceType": { 634 | "Ref": "ServerInstanceType" 635 | }, 636 | "IamInstanceProfile": { 637 | "Ref": "ConsulInstanceProfile" 638 | }, 639 | "KeyName": { 640 | "Ref": "KeyName" 641 | }, 642 | "NetworkInterfaces": [ 643 | { 644 | "GroupSet": [ 645 | { 646 | "Ref": "ConsulServerSecurityGroup" 647 | }, 648 | { 649 | "Ref": "ConsulAgentSecurityGroup" 650 | }, 651 | { 652 | "Ref": "CommonSecurityGroup" 653 | } 654 | ], 655 | "AssociatePublicIpAddress": "true", 656 | "DeviceIndex": "0", 657 | "DeleteOnTermination": "true", 658 | "SubnetId": { 659 | "Ref": "SubnetId" 660 | } 661 | } 662 | ], 663 | "Tags": [ 664 | { 665 | "Key": "Name", 666 | "Value": "ConsulServer" 667 | }, 668 | { 669 | "Key": "Application", 670 | "Value": { 671 | "Ref": "AWS::StackName" 672 | } 673 | } 674 | ], 675 | "UserData": { 676 | "Fn::Base64": { 677 | "Fn::Join": [ 678 | "", 679 | [ 680 | "#!/bin/bash -xe\n", 681 | "yum update -y\n", 682 | "yum update -y aws-cfn-bootstrap\n", 683 | "# Install the files and packages from the metadata\n", 684 | "/opt/aws/bin/cfn-init -v ", 685 | " --stack ", 686 | { 687 | "Ref": "AWS::StackName" 688 | }, 689 | " --resource ConsulServer ", 690 | " --configsets InstallAndRun ", 691 | " --region ", 692 | { 693 | "Ref": "AWS::Region" 694 | }, 695 | "\n", 696 | "# Signal the status from cfn-init\n", 697 | "/opt/aws/bin/cfn-signal -e $? ", 698 | " --stack ", 699 | { 700 | "Ref": "AWS::StackName" 701 | }, 702 | " --resource ConsulServer ", 703 | " --region ", 704 | { 705 | "Ref": "AWS::Region" 706 | }, 707 | "\n" 708 | ] 709 | ] 710 | } 711 | } 712 | }, 713 | "CreationPolicy": { 714 | "ResourceSignal": { 715 | "Count": "1", 716 | "Timeout": "PT15M" 717 | } 718 | } 719 | }, 720 | "EcsInstanceLc": { 721 | "Type": "AWS::AutoScaling::LaunchConfiguration", 722 | "DependsOn": "ConsulServer", 723 | "Metadata": { 724 | "AWS::CloudFormation::Init": { 725 | "configSets": { 726 | "InstallAndRun": [ 727 | "Install", 728 | "Configure", 729 | "StartContainers" 730 | ] 731 | }, 732 | "Install": { 733 | "files": { 734 | "/etc/sysconfig/docker": { 735 | "content": { 736 | "Fn::Join": [ 737 | " ", 738 | [ 739 | "OPTIONS='--dns 172.17.42.1 --dns", 740 | { 741 | "Ref": "AmazonDnsIp" 742 | }, 743 | "--dns-search service.consul'" 744 | ] 745 | ] 746 | }, 747 | "mode": "000755", 748 | "owner": "root", 749 | "group": "root" 750 | }, 751 | "/etc/consul/consul.json": { 752 | "content": { 753 | "Fn::Join": [ 754 | "", 755 | [ 756 | "{ \"leave_on_terminate\": true, \"recursors\": [ \"", 757 | { 758 | "Ref": "AmazonDnsIp" 759 | }, 760 | "\"] }" 761 | ] 762 | ] 763 | }, 764 | "mode": "000755", 765 | "owner": "root", 766 | "group": "root" 767 | }, 768 | "/etc/ecs/ecs.config": { 769 | "content": { 770 | "Fn::Join": [ 771 | "", 772 | [ 773 | "ECS_CLUSTER=", 774 | { 775 | "Ref": "EcsClusterName" 776 | }, "\n", 777 | "ECS_RESERVED_MEMORY=50" 778 | ] 779 | ] 780 | }, 781 | "mode": "000755", 782 | "owner": "root", 783 | "group": "root" 784 | } 785 | } 786 | }, 787 | "Configure": { 788 | "commands": { 789 | "01_create_consul_data_dir": { 790 | "command": { 791 | "Fn::Join": [ 792 | "", 793 | [ 794 | "mkdir -p /opt/consul" 795 | ] 796 | ] 797 | } 798 | }, 799 | "02_add_user_to_docker_group": { 800 | "command": { 801 | "Fn::Join": [ 802 | "", 803 | [ 804 | "usermod -a -G docker ec2-user" 805 | ] 806 | ] 807 | } 808 | }, 809 | "03_restart_docker": { 810 | "command": { 811 | "Fn::Join": [ 812 | "", 813 | [ 814 | "/sbin/service docker restart" 815 | ] 816 | ] 817 | } 818 | }, 819 | "04_pause_to_wait_for_docker_restart": { 820 | "command": { 821 | "Fn::Join": [ 822 | "", 823 | [ 824 | "/bin/sleep 5" 825 | ] 826 | ] 827 | } 828 | }, 829 | "05_start_ecs_if_not_running": { 830 | "command": { 831 | "Fn::Join": [ 832 | "", 833 | [ 834 | "[[ $(/sbin/status ecs) =~ \"running\" ]] || /sbin/start ecs" 835 | ] 836 | ] 837 | } 838 | }, 839 | "06_pull_consul_image": { 840 | "command": { 841 | "Fn::Join": [ 842 | "", 843 | [ 844 | "docker pull progrium/consul" 845 | ] 846 | ] 847 | } 848 | }, 849 | "07_pull_registrator_image": { 850 | "command": { 851 | "Fn::Join": [ 852 | "", 853 | [ 854 | "docker pull gliderlabs/registrator" 855 | ] 856 | ] 857 | } 858 | } 859 | } 860 | }, 861 | "StartContainers": { 862 | "commands": { 863 | "01_start_consul_docker_container": { 864 | "command": { 865 | "Fn::Join": [ 866 | " ", 867 | [ 868 | "docker run -d --restart=always -p 8301:8301 -p 8301:8301/udp", 869 | "-p 8400:8400 -p 8500:8500 -p 53:53/udp", 870 | "-v /opt/consul:/data -v /var/run/docker.sock:/var/run/docker.sock", 871 | "-v /etc/consul:/etc/consul", 872 | "-h $(curl -s http://169.254.169.254/latest/meta-data/instance-id)", 873 | "--name consul-agent progrium/consul -join", 874 | { 875 | "Fn::GetAtt": [ 876 | "ConsulServer", 877 | "PrivateIp" 878 | ] 879 | }, 880 | "-advertise $(curl -s http://169.254.169.254/latest/meta-data/local-ipv4) -dc", 881 | { 882 | "Fn::FindInMap": [ 883 | "DcMap", 884 | { 885 | "Ref": "AWS::Region" 886 | }, 887 | "Value" 888 | ] 889 | }, 890 | "-config-file /etc/consul/consul.json" 891 | ] 892 | ] 893 | } 894 | }, 895 | "02_start_registrator_docker_container": { 896 | "command": { 897 | "Fn::Join": [ 898 | " ", 899 | [ 900 | "docker run -d --restart=always -v /var/run/docker.sock:/tmp/docker.sock", 901 | "-h $(curl -s http://169.254.169.254/latest/meta-data/instance-id)", 902 | "--name consul-registrator gliderlabs/registrator:latest", 903 | "-ip $(curl -s http://169.254.169.254/latest/meta-data/local-ipv4)", 904 | "consul://$(curl -s http://169.254.169.254/latest/meta-data/local-ipv4):8500" 905 | ] 906 | ] 907 | } 908 | } 909 | } 910 | } 911 | } 912 | }, 913 | "Properties": { 914 | "ImageId": { 915 | "Fn::FindInMap": [ 916 | "EcsNodeAmiMap", 917 | { 918 | "Ref": "AWS::Region" 919 | }, 920 | "AMI" 921 | ] 922 | }, 923 | "InstanceType": { 924 | "Ref": "EcsInstanceType" 925 | }, 926 | "AssociatePublicIpAddress": true, 927 | "IamInstanceProfile": { 928 | "Ref": "ConsulInstanceProfile" 929 | }, 930 | "SecurityGroups": [ 931 | { 932 | "Ref": "ConsulAgentSecurityGroup" 933 | }, 934 | { 935 | "Ref": "CommonSecurityGroup" 936 | } 937 | ], 938 | "KeyName": { 939 | "Ref": "KeyName" 940 | }, 941 | "UserData": { 942 | "Fn::Base64": { 943 | "Fn::Join": [ 944 | "", 945 | [ 946 | "#!/bin/bash -xe\n", 947 | "yum update -y\n", 948 | "yum install -y aws-cfn-bootstrap\n", 949 | "# Install the files and packages from the metadata\n", 950 | "/opt/aws/bin/cfn-init -v ", 951 | " --stack ", 952 | { 953 | "Ref": "AWS::StackName" 954 | }, 955 | " --resource EcsInstanceLc ", 956 | " --configsets InstallAndRun ", 957 | " --region ", 958 | { 959 | "Ref": "AWS::Region" 960 | }, 961 | "\n", 962 | "# Signal the status from cfn-init\n", 963 | "/opt/aws/bin/cfn-signal -e $? ", 964 | " --stack ", 965 | { 966 | "Ref": "AWS::StackName" 967 | }, 968 | " --resource EcsInstanceAsg ", 969 | " --region ", 970 | { 971 | "Ref": "AWS::Region" 972 | }, 973 | "\n" 974 | ] 975 | ] 976 | } 977 | } 978 | } 979 | }, 980 | "EcsInstanceAsg": { 981 | "Type": "AWS::AutoScaling::AutoScalingGroup", 982 | "Properties": { 983 | "AvailabilityZones": [ 984 | { 985 | "Ref": "AZ" 986 | } 987 | ], 988 | "VPCZoneIdentifier": [ 989 | { 990 | "Ref": "SubnetId" 991 | } 992 | ], 993 | "LaunchConfigurationName": { 994 | "Ref": "EcsInstanceLc" 995 | }, 996 | "MinSize": { 997 | "Ref": "ClusterSize" 998 | }, 999 | "MaxSize": { 1000 | "Ref": "ClusterSize" 1001 | }, 1002 | "DesiredCapacity": { 1003 | "Ref": "ClusterSize" 1004 | }, 1005 | "Tags": [ 1006 | { 1007 | "Key": "Application", 1008 | "Value": { 1009 | "Ref": "AWS::StackName" 1010 | }, 1011 | "PropagateAtLaunch": "true" 1012 | }, 1013 | { 1014 | "Key": "Name", 1015 | "Value": "ECS Instance", 1016 | "PropagateAtLaunch": "true" 1017 | } 1018 | ] 1019 | } 1020 | } 1021 | }, 1022 | "Outputs": { 1023 | "ConsulServerURL": { 1024 | "Description": "Name of the ConsulServer instance", 1025 | "Value": { 1026 | "Fn::Join": [ 1027 | "", 1028 | [ 1029 | "http://", 1030 | { 1031 | "Fn::GetAtt": [ 1032 | "ConsulServer", 1033 | "PublicDnsName" 1034 | ] 1035 | }, 1036 | "/ui" 1037 | ] 1038 | ] 1039 | } 1040 | }, 1041 | "EcsInstanceAsgName": { 1042 | "Description": "Auto Scaling Group Name for ECS Instances", 1043 | "Value": { 1044 | "Ref": "EcsInstanceAsg" 1045 | } 1046 | } 1047 | } 1048 | } 1049 | -------------------------------------------------------------------------------- /stock-price/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ruby:2.1-onbuild 2 | EXPOSE 4567 3 | 4 | RUN chmod u+x ./stocks.rb 5 | 6 | CMD ["./stocks.rb"] 7 | -------------------------------------------------------------------------------- /stock-price/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | gem 'sinatra' 3 | -------------------------------------------------------------------------------- /stock-price/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | mustermann (1.1.1) 5 | ruby2_keywords (~> 0.0.1) 6 | rack (2.2.3) 7 | rack-protection (2.0.8.1) 8 | rack 9 | ruby2_keywords (0.0.2) 10 | sinatra (2.0.8.1) 11 | mustermann (~> 1.0) 12 | rack (~> 2.0) 13 | rack-protection (= 2.0.8.1) 14 | tilt (~> 2.0) 15 | tilt (2.0.10) 16 | 17 | PLATFORMS 18 | ruby 19 | 20 | DEPENDENCIES 21 | sinatra 22 | 23 | BUNDLED WITH 24 | 2.1.4 25 | -------------------------------------------------------------------------------- /stock-price/stocks.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'sinatra' 3 | require 'net/http' 4 | require 'json' 5 | require 'csv' 6 | 7 | set :bind, '0.0.0.0' 8 | 9 | # The URI to do the stock symbol lookup. 10 | # Returns a JSON document with stock name and price. 11 | get '/stock/:name' do 12 | "Stock: #{params['name']}" 13 | result = lookup_stock(params['name']) 14 | puts result 15 | convert_to_JSON(params['name'], result) if !result.nil? 16 | end 17 | 18 | # The URI for the health check 19 | get '/health' do 20 | "OK" 21 | end 22 | 23 | # Function to do the stock price lookup. 24 | # Makes a call to the Yahoo Finance API and returns result 25 | def lookup_stock(name) 26 | uri = URI("http://download.finance.yahoo.com/d/quotes.csv?") 27 | params = { :s => name, :f => 'nl1r' } 28 | uri.query = URI.encode_www_form(params) 29 | res = Net::HTTP.get_response(uri) 30 | res.body if res.is_a?(Net::HTTPSuccess) 31 | end 32 | 33 | # Converts CSV output from API call into a JSON document 34 | def convert_to_JSON(name, response) 35 | output = CSV.parse(response).flatten 36 | result = { :symbol => name, 37 | :name => output[0], 38 | :price => output[1] } 39 | result.to_json 40 | end 41 | -------------------------------------------------------------------------------- /weather/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ruby:2.1-onbuild 2 | EXPOSE 4567 3 | 4 | RUN chmod u+x ./weather.rb 5 | 6 | CMD ["./weather.rb"] 7 | -------------------------------------------------------------------------------- /weather/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | gem 'sinatra' 3 | -------------------------------------------------------------------------------- /weather/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | mustermann (1.1.1) 5 | ruby2_keywords (~> 0.0.1) 6 | rack (2.2.3) 7 | rack-protection (2.0.8.1) 8 | rack 9 | ruby2_keywords (0.0.2) 10 | sinatra (2.0.8.1) 11 | mustermann (~> 1.0) 12 | rack (~> 2.0) 13 | rack-protection (= 2.0.8.1) 14 | tilt (~> 2.0) 15 | tilt (2.0.10) 16 | 17 | PLATFORMS 18 | ruby 19 | 20 | DEPENDENCIES 21 | sinatra 22 | 23 | BUNDLED WITH 24 | 2.1.4 25 | -------------------------------------------------------------------------------- /weather/weather.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'sinatra' 3 | require 'net/http' 4 | require 'json' 5 | require 'logger' 6 | 7 | set :bind, '0.0.0.0' 8 | 9 | # do the configuration of the web server 10 | configure do 11 | 12 | enable :logging 13 | 14 | # get the temperature scale from an enviornment variable 15 | temp_scale = ENV['TEMP_SCALE'] 16 | case temp_scale 17 | when 'C' 18 | set :is_metric => true 19 | when 'F' 20 | set :is_metric => false 21 | else 22 | set :is_metric => true 23 | end 24 | 25 | # get the Open Weathermap API Key from an enviornment variable 26 | set :api_key => ENV['API_KEY'] 27 | end 28 | 29 | 30 | # The URI to do a temperature lookup for the specified city. 31 | # Returns a JSON document with city name, country and temperature. 32 | get '/weather/:city' do 33 | "Weather: #{params['city']}" 34 | result = lookup_weather(params['city']) 35 | logger.info "Response from external API is: #{result}" 36 | convert_to_JSON(params['city'], result) if !result.nil? 37 | end 38 | 39 | # The URI for the health check 40 | get '/health' do 41 | "OK" 42 | end 43 | 44 | # Function to do the city weather lookup. 45 | # Makes a call to the Open Weather Map API and returns result 46 | def lookup_weather(city) 47 | uri = URI("http://api.openweathermap.org/data/2.5/weather") 48 | params = { :q => city, :units => (settings.is_metric ? "metric" : "imperial"), :APPID => settings.api_key } 49 | uri.query = URI.encode_www_form(params) 50 | logger.info "URI is: #{uri}" 51 | res = Net::HTTP.get_response(uri) 52 | res.body if res.is_a?(Net::HTTPSuccess) 53 | end 54 | 55 | # Converts JSON result from API call into a smaller JSON document 56 | def convert_to_JSON(city, response) 57 | output = JSON.parse(response) 58 | result = { :city => output['name'], 59 | :country => output['sys']['country'], 60 | :temp => output['main']['temp'], 61 | :format => (settings.is_metric ? "Celsius" : "Farenheit") } 62 | result.to_json 63 | end 64 | --------------------------------------------------------------------------------