├── .classpath ├── .gitignore ├── .project ├── .travis.yml ├── CF_spring_cloud_aws_sample.yml ├── LICENSE ├── README.md ├── pom.xml └── src └── main ├── docker └── Dockerfile ├── java └── es │ └── urjc │ └── code │ └── daw │ └── tablonanuncios │ ├── Anuncio.java │ ├── AnunciosRepository.java │ ├── Application.java │ └── TablonController.java └── resources ├── application-dev.properties ├── application-prod.properties ├── application.properties ├── bootstrap-dev.properties ├── bootstrap-prod.properties ├── bootstrap.properties ├── static └── nuevoAnuncio.html └── templates ├── anuncio_guardado.html ├── error.html ├── tablon.html └── ver_anuncio.html /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | .settings 3 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | spring-cloud-aws-sample 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.common.project.facet.core.builder 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.springframework.ide.eclipse.core.springbuilder 20 | 21 | 22 | 23 | 24 | org.springframework.ide.eclipse.boot.validation.springbootbuilder 25 | 26 | 27 | 28 | 29 | org.eclipse.m2e.core.maven2Builder 30 | 31 | 32 | 33 | 34 | 35 | org.springframework.ide.eclipse.core.springnature 36 | org.eclipse.jdt.core.javanature 37 | org.eclipse.m2e.core.maven2Nature 38 | org.eclipse.wst.common.project.facet.core.nature 39 | 40 | 41 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: trusty 2 | sudo: required 3 | 4 | before_install: 5 | - sudo add-apt-repository -y ppa:openjdk-r/ppa 6 | - sudo apt-get update 7 | - sudo apt-get install -y openjdk-8-jdk 8 | 9 | language: java 10 | 11 | script: 12 | - docker login -u $DOCKERHUB_USERNAME -p $DOCKERHUB_PASS 13 | - mvn package docker:build -DpushImage 14 | -------------------------------------------------------------------------------- /CF_spring_cloud_aws_sample.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: AWS Cloud Formation Spring Cloud Aws Example 3 | 4 | Parameters: 5 | 6 | DatabasePassword: 7 | Description: Database Password 8 | Type: String 9 | NoEcho: true 10 | Default: your_password 11 | 12 | KeyName: 13 | Description: "Name of an existing EC2 KeyPair to enable SSH access to the instance." 14 | Type: AWS::EC2::KeyPair::KeyName 15 | ConstraintDescription: "must be the name of an existing EC2 KeyPair." 16 | 17 | Mappings: 18 | RegionMap: 19 | eu-west-1: 20 | AMI: ami-02df9ea15c1778c9c 21 | 22 | Resources: 23 | 24 | SpringCloudAwsRole: 25 | Type: 'AWS::IAM::Role' 26 | Properties: 27 | AssumeRolePolicyDocument: 28 | Version: 2012-10-17 29 | Statement: 30 | - Effect: Allow 31 | Principal: 32 | Service: 33 | - ec2.amazonaws.com 34 | Action: 35 | - 'sts:AssumeRole' 36 | Path: / 37 | Policies: 38 | - PolicyName: SpringCloudAwsRolePolicy 39 | PolicyDocument: 40 | Version: 2012-10-17 41 | Statement: 42 | - Effect: Allow 43 | Action: 44 | - 'rds:DescribeDBInstances' 45 | - 's3:PutObject' 46 | - 's3:GetObject' 47 | - 's3:DeleteObject' 48 | - 'secretsmanager:DescribeSecret' 49 | - 'secretsmanager:GetSecretValue' 50 | - 'secretsmanager:ListSecrets' 51 | - 'secretsmanager:ListSecretVersionIds' 52 | 53 | Resource: '*' 54 | RoleName: SpringCloudAwsSampleRole 55 | 56 | SpringCloudAwsInstanceProfile: 57 | Type: 'AWS::IAM::InstanceProfile' 58 | DependsOn: SpringCloudAwsRole 59 | Properties: 60 | Path: / 61 | Roles: 62 | - SpringCloudAwsSampleRole 63 | 64 | SpringCloudAwsRDS: 65 | Type: AWS::RDS::DBInstance 66 | DependsOn: 67 | - SpringCloudAwsRole 68 | Properties: 69 | AllocatedStorage: '5' 70 | DBInstanceIdentifier: springaws 71 | DBInstanceClass: db.t2.micro 72 | Engine: MySQL 73 | DBName: springaws 74 | MasterUsername: springaws 75 | MasterUserPassword: !Ref DatabasePassword 76 | MultiAZ: false 77 | PubliclyAccessible: true 78 | DBSecurityGroups: 79 | - !Ref SpringCloudAwsRDSSecurityGroup 80 | DeletionPolicy: Delete 81 | 82 | SpringCloudAwsRDSSecurityGroup: 83 | Type: AWS::RDS::DBSecurityGroup 84 | Properties: 85 | GroupDescription : Security Group for RDS public Access 86 | DBSecurityGroupIngress: 87 | - CIDRIP: 0.0.0.0/0 88 | 89 | SpringCloudAwsServerSecurityGroup: 90 | Type: 'AWS::EC2::SecurityGroup' 91 | Properties: 92 | GroupDescription: Security Group for Spring server 93 | SecurityGroupIngress: 94 | - IpProtocol: tcp 95 | FromPort: 22 96 | ToPort: 22 97 | CidrIp: 0.0.0.0/0 98 | - IpProtocol: tcp 99 | FromPort: 80 100 | ToPort: 80 101 | CidrIp: 0.0.0.0/0 102 | 103 | S3bucket: 104 | Type: 'AWS::S3::Bucket' 105 | Properties: 106 | BucketName: spring-cloud-aws-sample-s3 107 | DeletionPolicy: Delete 108 | 109 | BucketPolicy: 110 | Type: 'AWS::S3::BucketPolicy' 111 | DependsOn: S3bucket 112 | Properties: 113 | Bucket: 'spring-cloud-aws-sample-s3' 114 | PolicyDocument: 115 | Version: '2012-10-17' 116 | Statement: 117 | - Sid: 'AddPerm' 118 | Principal: '*' 119 | Action: 's3:GetObject' 120 | Effect: 'Allow' 121 | Resource: 122 | - 'arn:aws:s3:::spring-cloud-aws-sample-s3/*' 123 | 124 | SpringCloudAwsEC2Instance: 125 | Type: AWS::EC2::Instance 126 | DependsOn: SpringCloudAwsRDS 127 | Metadata: 128 | Comment: Spring Using AWS services 129 | AWS::CloudFormation::Init: 130 | config: 131 | files: 132 | "/etc/cfn/cfn-hup.conf": 133 | content: !Sub | 134 | [main] 135 | stack=${AWS::StackId} 136 | region=${AWS::Region} 137 | mode: "000400" 138 | owner: "root" 139 | group: "root" 140 | "/etc/cfn/hooks.d/cfn-auto-reloader.conf": 141 | content: !Sub | 142 | [cfn-auto-reloader-hook] 143 | triggers=post.update 144 | path=Resources.SpringCloudAwsEC2Instance.Metadata.AWS::CloudFormation::Init 145 | action=/usr/local/bin/cfn-init -v --stack ${AWS::StackName} --resource SpringCloudAwsEC2Instance --region ${AWS::Region} 146 | mode: "000400" 147 | owner: "root" 148 | group: "root" 149 | "/usr/local/bin/installSoftware.sh": 150 | content: | 151 | #!/bin/bash -xe 152 | set -eu -o pipefail 153 | # installing necessary software 154 | apt-get update 155 | apt-get install -y awscli python-pip 156 | 157 | pip install --upgrade awscli 158 | 159 | curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - 160 | add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable" 161 | apt-get update 162 | apt-get install -y docker-ce 163 | mode: "000755" 164 | owner: "root" 165 | group: "root" 166 | "/usr/local/bin/check_app_ready.sh": 167 | content: | 168 | #!/bin/bash -xe 169 | set -eu -o pipefail 170 | 171 | sleep 1m 172 | 173 | while true 174 | do 175 | HTTP_STATUS=$(curl -Ik http://localhost/ | head -n1 | awk '{print $2}') 176 | if [ $HTTP_STATUS == 200 ]; then 177 | break 178 | fi 179 | sleep 1 180 | done 181 | 182 | mode: "000755" 183 | owner: "root" 184 | group: "root" 185 | Properties: 186 | ImageId: !FindInMap [RegionMap, !Ref 'AWS::Region', AMI] 187 | InstanceType: t2.micro 188 | KeyName: !Ref KeyName 189 | IamInstanceProfile: !Ref SpringCloudAwsInstanceProfile 190 | SecurityGroupIds: 191 | - !GetAtt 'SpringCloudAwsServerSecurityGroup.GroupId' 192 | Tags: 193 | - Key: Name 194 | Value: 'spring-aws-cloud-sample' 195 | UserData: 196 | "Fn::Base64": 197 | !Sub | 198 | #!/bin/bash -xe 199 | set -eu -o pipefail 200 | apt-get update 201 | apt-get install -y python-pip 202 | pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz 203 | 204 | cfn-init --region ${AWS::Region} --stack ${AWS::StackId} --resource SpringCloudAwsEC2Instance 205 | 206 | # Install needed software 207 | /usr/local/bin/installSoftware.sh || { echo "Error installing software"; exit 1; } 208 | 209 | # Run App 210 | docker run -d -e PROG_OPTS='--spring.profiles.active=prod' -p 80:8080 codeurjc/spring-cloud-aws-sample:latest 211 | 212 | /usr/local/bin/check_app_ready.sh || { echo "Error installing software"; exit 1; } 213 | 214 | # sending the finish call 215 | /usr/local/bin/cfn-signal -e $? --stack ${AWS::StackId} --resource WaitCondition --region ${AWS::Region} 216 | 217 | WaitCondition: 218 | Type: AWS::CloudFormation::WaitCondition 219 | CreationPolicy: 220 | ResourceSignal: 221 | Timeout: PT40M 222 | Count: 1 223 | 224 | Outputs: 225 | Application: 226 | Description: "Deployed Spring Application" 227 | Value: !Join 228 | - '' 229 | - - 'http://' 230 | - !GetAtt SpringCloudAwsEC2Instance.PublicDnsName -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring cloud aws sample 2 | 3 | This is a sample application for demonstration purposes only. It is a very simple application devoted to managing advertisements (actually, it doesn't allow deletion and update of ads). The idea is demonstrate Spring Cloud AWS capabilities. In order to run it, you need a minimum AWS configuration (see below). 4 | 5 | The application allows users to create ads with a picture. Ads are stored in a RDS database in AWS. The project is configured to use MySQL, but that can be changed to use a different database (for instance, PostgreSQL). Pictures within ads are stored in a bucket in S3. 6 | 7 | Also the application has two different Spring profiles: `dev` and `prod`. While running `prod`, the application gets all properties(username, password, databasename...) to connect to a RDS database using AWS Secrets Manager for security purposes. 8 | 9 | ## Prerequisites 10 | 11 | ### Create an RDS Instance 12 | 13 | **WARNING**: These instructions allow you to run and test the application from within your development environment (i.e., without deploying it to AWS) using an RDS instance open to the world, which is something you should avoid in production. 14 | 15 | First, create a _security group_ that will be used to allow ingress connections from outside AWS. Whithin the security group just created, create a new _access rule_ with the following configuration: 16 | 17 | * Type: MySQL/Aurora 18 | * Source: Anywhere 19 | * CIDR: 0.0.0.0/0 20 | 21 | Then, create an RDS instance, with these properties: 22 | 23 | * Engine MySQL 24 | * Type dev/test 25 | * DB Instance Class: t2.micro 26 | * Multizone AZ: no 27 | * DB Instance identifier: springaws (we will provide this as app argument cloud.aws.rds.dbInstanceIdentifier) 28 | * Master username: springaws (we will provide this as app argument cloud.aws.rds.springaws.username) 29 | * Master password: > (we will provide this as app argument cloud.aws.rds.springaws.password) 30 | * Ensure Default VPC is enabled 31 | * Ensure Publicly accessible is yes 32 | * VPC security group: choose the security group previously created 33 | * Database name: springaws 34 | * Launch!! 35 | 36 | ### Create an S3 bucket 37 | 38 | Create an S3 bucket, name it `spring-cloud-aws-sample-s3` and give read permissions to anonymous users. Just copy and paste this aws policy to enable anonymous read access: 39 | 40 | { 41 | "Version":"2012-10-17", 42 | "Statement":[ 43 | { 44 | "Sid":"AddPerm", 45 | "Effect":"Allow", 46 | "Principal": "*", 47 | "Action":["s3:GetObject"], 48 | "Resource":["arn:aws:s3:::spring-cloud-aws-sample-s3/*"] 49 | } 50 | ] 51 | } 52 | 53 | ### AWS Secrets Manager 54 | 55 | Create a new secret named as: `/secrets-app/springaws_prod`. You can insert your desired values but if you want to use the previously created RDS database just put the next key-values: 56 | 57 | | Secret Key | Secret Value | 58 | |-------------------------------------|---------------| 59 | | cloud.aws.rds.dbInstanceIdentifier | springaws | 60 | | cloud.aws.rds.springaws.password || 61 | | cloud.aws.rds.springaws.username | springaws | 62 | | cloud.aws.rds.springaws.databaseName| springaws | 63 | 64 | 65 | ### To run locally 66 | 67 | Some configurations are required in your AWS account for this sample to work. Basically, an _S3 bucket_ (by default `spring-cloud-aws-sample-s3` is used, but it can be changed using `cloud.aws.s3.bucket` property), and an _RDS MySQL instance_ open to the world. Additionally, we need an _IAM user_ with access key and programmatic access to AWS API so that we can access AWS resources from our development machine. 68 | 69 | #### Create an IAM User 70 | 71 | - Enable programmatic access 72 | - Generate an access key for the user 73 | - Give the user the following permissions: 74 | - AmazonS3FullAccess 75 | - AmazonRDSFullAccess 76 | - SecretsManagerReadWrite 77 | 78 | ### To run on EC2 79 | 80 | #### Create an IAM role 81 | 82 | Create an IAM role with the following properties: 83 | 84 | - EC2 role (i.e., a role to be attached to EC2 instances) 85 | - Policies: 86 | - AmazonS3FullAccess 87 | - AmazonRDSFullAccess 88 | - SecretsManagerReadWrite 89 | 90 | **WARNING**: It's a good practice to limit policies and not give all available permissions. We're selecting FullAccess as a proof of concept. Real deployment environments must have more restrictive policies. 91 | 92 | #### Create an EC2 instance 93 | 94 | It has been tested with an instance with the following properties: 95 | 96 | * AMI: Ubuntu 18.04 97 | * Type: t2.micro 98 | * Storage: 20Gb 99 | * Security group: choose or create one with ports 22 and 8080 opened 100 | * Attach the IAM role created previously 101 | 102 | Once the instance has been started, ssh'd into the machine and issue the following commands: 103 | 104 | ``` 105 | sudo apt-get update 106 | sudo apt-get install openjdk-8-jre-headless 107 | ``` 108 | 109 | Then from your own machine, build the jar file and upload it to your EC2 instance: 110 | 111 | ``` 112 | mvn package -DskipTests 113 | scp -i spring-cloud-aws-sample-0.2.0.jar ubuntu@:/home/ubuntu/ 114 | ``` 115 | 116 | ## Run the application 117 | 118 | ### Locally (dev) 119 | 120 | If you have AWS CLI installed in your machine, spring-cloud-aws reads credentials automatically from your machine while trying to use AWS services, but If you don't have it installed, you need to specify the credentials in the `application-dev.properties` file or pass these as parameters launching the jar file: 121 | 122 | 123 | ``` 124 | cloud.aws.credentials.accessKey="your key" 125 | cloud.aws.credentials.secretKey="your secret" 126 | ``` 127 | 128 | If you have AWS CLI you can just run: 129 | 130 | git clone https://github.com/codeurjc/spring-cloud-aws-sample 131 | cd spring-cloud-aws-sample 132 | mvn package 133 | cd target 134 | java -jar spring-cloud-aws-sample-0.2.0-SNAPSHOT.jar \ 135 | --spring.profiles.active=dev \ 136 | --cloud.aws.rds.dbInstanceIdentifier=springaws \ 137 | --cloud.aws.rds.springaws.password= \ 138 | --cloud.aws.rds.springaws.username=springaws \ 139 | --cloud.aws.rds.springaws.databaseName=springaws 140 | 141 | 142 | 143 | ### On AWS (prod) 144 | 145 | If your EC2 instance has the appropriate role (see prerequisites above), and the jar file has been uploaded, and you have created your Secret 146 | 147 | java -jar spring-cloud-aws-sample-0.1.0-SNAPSHOT.jar \ 148 | --spring.profiles.active=prod 149 | 150 | As you can see is not necessary to put database credentials to run the application, it gets the necessary values from AWS Secret Manager. 151 | 152 | ### Using CloudFormation 153 | 154 | To run with CloudFormation is not necessary to create any AWS resources, only secrets. Steps are the following 155 | 156 | 1. Insert your secret properties as explained in section [AWS Secrets Manager](#aws-secrets-manager) 157 | 2. As parameters to run your stack, you'll need to specify: 158 | - Database password 159 | - Key Name (for ssh) 160 | 3. Go to your application by click to the link given at the output section of the cloudformation after the stack have been created. 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | es.urjc.code 7 | spring-cloud-aws-sample 8 | 0.2.0-SNAPSHOT 9 | jar 10 | 11 | 12 | org.springframework.boot 13 | spring-boot-starter-parent 14 | 2.2.1.RELEASE 15 | 16 | 17 | 18 | 19 | UTF-8 20 | 1.8 21 | codeurjc 22 | 23 | 24 | spring-cloud-aws-sample 25 | Sample project demonstrating using S3 and a securized access to RDS using AWS Secrets Manager with Spring Cloud AWS 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-mustache 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-data-jpa 39 | 40 | 41 | org.springframework.cloud 42 | spring-cloud-aws-autoconfigure 43 | 44 | 45 | org.springframework.cloud 46 | spring-cloud-starter-aws 47 | 48 | 49 | org.springframework.cloud 50 | spring-cloud-starter-aws-jdbc 51 | 52 | 53 | 54 | org.springframework.cloud 55 | spring-cloud-starter-aws-secrets-manager-config 56 | 57 | 58 | 59 | mysql 60 | mysql-connector-java 61 | 62 | 63 | 64 | org.springframework.boot 65 | spring-boot-devtools 66 | 67 | 68 | 69 | 70 | 71 | 72 | org.springframework.cloud 73 | spring-cloud-dependencies 74 | Greenwich.RELEASE 75 | pom 76 | import 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | org.springframework.boot 85 | spring-boot-maven-plugin 86 | 87 | 88 | com.spotify 89 | docker-maven-plugin 90 | 0.4.11 91 | 92 | ${docker.image.prefix}/${project.artifactId} 93 | src/main/docker 94 | ${project.version} 95 | true 96 | 97 | 98 | / 99 | ${project.build.directory} 100 | ${project.build.finalName}.jar 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /src/main/docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:8u111-jre-alpine 2 | VOLUME /tmp 3 | ADD spring-cloud-aws-sample-0.2.0-SNAPSHOT.jar app.jar 4 | RUN sh -c 'touch /app.jar' 5 | ENV JAVA_OPTS="" 6 | ENV PROG_OPTS="" 7 | ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar $PROG_OPTS" ] -------------------------------------------------------------------------------- /src/main/java/es/urjc/code/daw/tablonanuncios/Anuncio.java: -------------------------------------------------------------------------------- 1 | package es.urjc.code.daw.tablonanuncios; 2 | 3 | import java.net.URL; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | 10 | @Entity 11 | public class Anuncio { 12 | 13 | @Id 14 | @GeneratedValue(strategy = GenerationType.AUTO) 15 | private long id; 16 | 17 | private String nombre; 18 | private String asunto; 19 | private String comentario; 20 | private URL foto; 21 | 22 | public Anuncio() {} 23 | 24 | public Anuncio(String nombre, String asunto, String comentario) { 25 | super(); 26 | this.nombre = nombre; 27 | this.asunto = asunto; 28 | this.comentario = comentario; 29 | } 30 | 31 | public String getNombre() { 32 | return nombre; 33 | } 34 | 35 | public void setNombre(String nombre) { 36 | this.nombre = nombre; 37 | } 38 | 39 | public String getAsunto() { 40 | return asunto; 41 | } 42 | 43 | public void setAsunto(String asunto) { 44 | this.asunto = asunto; 45 | } 46 | 47 | public String getComentario() { 48 | return comentario; 49 | } 50 | 51 | public void setComentario(String comentario) { 52 | this.comentario = comentario; 53 | } 54 | 55 | public URL getFoto() { 56 | return foto; 57 | } 58 | 59 | public void setFoto(URL foto) { 60 | this.foto = foto; 61 | } 62 | 63 | @Override 64 | public String toString() { 65 | return "Anuncio [nombre=" + nombre + ", asunto=" + asunto + ", comentario=" + comentario + "]"; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/es/urjc/code/daw/tablonanuncios/AnunciosRepository.java: -------------------------------------------------------------------------------- 1 | package es.urjc.code.daw.tablonanuncios; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface AnunciosRepository extends JpaRepository { 6 | 7 | } -------------------------------------------------------------------------------- /src/main/java/es/urjc/code/daw/tablonanuncios/Application.java: -------------------------------------------------------------------------------- 1 | package es.urjc.code.daw.tablonanuncios; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.aws.jdbc.config.annotation.EnableRdsInstance; 6 | 7 | @SpringBootApplication 8 | @EnableRdsInstance(dbInstanceIdentifier="${cloud.aws.rds.dbInstanceIdentifier}", databaseName="${cloud.aws.rds.springaws.databaseName}", 9 | username="${cloud.aws.rds.springaws.username}", password="${cloud.aws.rds.springaws.password}") 10 | public class Application { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(Application.class, args); 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/java/es/urjc/code/daw/tablonanuncios/TablonController.java: -------------------------------------------------------------------------------- 1 | package es.urjc.code.daw.tablonanuncios; 2 | 3 | import javax.annotation.PostConstruct; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.ui.Model; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RequestParam; 13 | import org.springframework.web.multipart.MultipartFile; 14 | 15 | import com.amazonaws.services.s3.AmazonS3; 16 | import com.amazonaws.services.s3.model.ObjectMetadata; 17 | import com.amazonaws.services.s3.transfer.TransferManager; 18 | import com.amazonaws.services.s3.transfer.TransferManagerBuilder; 19 | 20 | @Controller 21 | public class TablonController { 22 | 23 | @Autowired 24 | private AnunciosRepository repository; 25 | 26 | @Autowired 27 | private AmazonS3 s3; 28 | 29 | @Value("${cloud.aws.s3.bucket}") 30 | private String bucket; 31 | 32 | @PostConstruct 33 | public void init() { 34 | repository.save(new Anuncio("Pepe", "Hola caracola", "A description")); 35 | repository.save(new Anuncio("Juan", "Hola caracola", "A description")); 36 | } 37 | 38 | @RequestMapping("/") 39 | public String tablon(Model model, Pageable page) { 40 | 41 | model.addAttribute("anuncios", repository.findAll(page)); 42 | 43 | return "tablon"; 44 | } 45 | 46 | @RequestMapping("/anuncio/nuevo") 47 | public String nuevoAnuncio(Model model, 48 | @RequestParam String nombre, 49 | @RequestParam String asunto, 50 | @RequestParam String comentario, 51 | @RequestParam String filename, 52 | @RequestParam MultipartFile file) { 53 | 54 | if (!file.isEmpty()) { 55 | try { 56 | ObjectMetadata objectMetadata = new ObjectMetadata(); 57 | objectMetadata.setContentType(file.getContentType()); 58 | 59 | TransferManager transferManager = TransferManagerBuilder.defaultTransferManager(); 60 | transferManager.upload(bucket, filename, file.getInputStream(), objectMetadata); 61 | 62 | } catch (Exception e) { 63 | model.addAttribute("message", "You failed to upload " + filename + " => " + e.getMessage()); 64 | return "error"; 65 | } 66 | } else { 67 | model.addAttribute("message", "You failed to upload " + filename + " because the file was empty."); 68 | return "error"; 69 | } 70 | 71 | Anuncio anuncio = new Anuncio(nombre, asunto, comentario); 72 | anuncio.setFoto(s3.getUrl(bucket, filename)); 73 | 74 | repository.save(anuncio); 75 | 76 | return "anuncio_guardado"; 77 | 78 | } 79 | 80 | @RequestMapping("/anuncio/{id}") 81 | public String verAnuncio(Model model, @PathVariable long id) { 82 | 83 | Anuncio anuncio = repository.findById(id).get(); 84 | 85 | model.addAttribute("hasFoto", anuncio.getFoto() != null); 86 | model.addAttribute("anuncio", anuncio); 87 | 88 | return "ver_anuncio"; 89 | } 90 | 91 | } -------------------------------------------------------------------------------- /src/main/resources/application-dev.properties: -------------------------------------------------------------------------------- 1 | ## Necessary to specify when AWS CLI is not installed 2 | #cloud.aws.credentials.accessKey="your key" 3 | #cloud.aws.credentials.secretKey="your secret" 4 | 5 | # RDS access 6 | cloud.aws.rds.dbInstanceIdentifier=springaws 7 | cloud.aws.rds.springaws.password=your_password 8 | cloud.aws.rds.springaws.username=springaws 9 | cloud.aws.rds.springaws.databaseName=springaws -------------------------------------------------------------------------------- /src/main/resources/application-prod.properties: -------------------------------------------------------------------------------- 1 | # RDS access 2 | cloud.aws.rds.dbInstanceIdentifier= 3 | cloud.aws.rds.springaws.password= 4 | cloud.aws.rds.springaws.username= 5 | cloud.aws.rds.springaws.databaseName= -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Application Name, neccesary for secrets manager 2 | spring.application.name=springaws 3 | 4 | spring.datasource.driverClassName=com.mysql.jdbc.Driver 5 | spring.jpa.hibernate.ddl-auto=create 6 | 7 | # Make html the default extension for mustache 8 | spring.mustache.suffix=.html 9 | 10 | # Spring cloud properties (can be specified at start time as --cloud.aws.region.static=eu-west-1) 11 | 12 | # Region (can be discovered dynamically when running within an EC2 instance 13 | cloud.aws.region.static=eu-west-1 14 | 15 | # Avoid trying to autodetect the stack when running in a manually deployed infrastructure 16 | cloud.aws.stack.auto=false 17 | 18 | # Credentials (unnecessary when running in an EC2 instance with a role having enough permissions for S3 and RDS) 19 | #cloud.aws.credentials.accessKey="key" 20 | #cloud.aws.credentials.secretKey="secret" 21 | 22 | # In AWS use this instead, and create an EC2 role 23 | cloud.aws.credentials.instanceProfile=true 24 | 25 | # S3 26 | cloud.aws.s3.bucket=spring-cloud-aws-sample-s3 -------------------------------------------------------------------------------- /src/main/resources/bootstrap-dev.properties: -------------------------------------------------------------------------------- 1 | # Spring AWS Secrets configuration 2 | aws.secretsmanager.enabled=false -------------------------------------------------------------------------------- /src/main/resources/bootstrap-prod.properties: -------------------------------------------------------------------------------- 1 | # Spring AWS Secrets configuration 2 | aws.secretsmanager.enabled=true -------------------------------------------------------------------------------- /src/main/resources/bootstrap.properties: -------------------------------------------------------------------------------- 1 | # Application Name, neccesary for secrets manager 2 | spring.application.name=springaws 3 | 4 | # Spring AWS Secrets configuration 5 | aws.secretsmanager.prefix=/secrets-app 6 | aws.secretsmanager.defaultContext=application 7 | aws.secretsmanager.profileSeparator=_ 8 | aws.secretsmanager.failFast=true 9 | aws.secretsmanager.name=springaws 10 | 11 | # Spring AWS Secrets configuration 12 | aws.secretsmanager.enabled=true -------------------------------------------------------------------------------- /src/main/resources/static/nuevoAnuncio.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 |

Nombre:

8 | 9 |

Asunto:

10 | 11 |

Comentario:

12 | 13 |

File to upload:

14 |
15 |

Name:

16 |
17 | 18 |
19 | 20 | -------------------------------------------------------------------------------- /src/main/resources/templates/anuncio_guardado.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |

El anuncio ha sido guardado correctamente

4 | Volver al tablón 5 | 6 | -------------------------------------------------------------------------------- /src/main/resources/templates/error.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Problemas al guardar el anuncio: {{message}}

4 | Volver al tablón 5 | 6 | -------------------------------------------------------------------------------- /src/main/resources/templates/tablon.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Tablón Anuncios

4 | {{#anuncios}} 5 | {{nombre}} {{asunto}}
6 | {{/anuncios}} 7 | 8 |
9 | Nuevo anuncio 10 | 11 | -------------------------------------------------------------------------------- /src/main/resources/templates/ver_anuncio.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Nombre: {{anuncio.nombre}}

4 |

Asunto: {{anuncio.asunto}}

5 |

Comentario: {{anuncio.comentario}}

6 | {{#hasFoto}} 7 |

{{anuncio.foto}}

8 | {{/hasFoto}} 9 | 10 | Volver al tablón 11 | 12 | --------------------------------------------------------------------------------