├── COPYING ├── LICENSE ├── NOTICE ├── README.md ├── cf-resources.json ├── cf-rules.json └── cf-validator.py /COPYING: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | CF-Validator 2 | Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws-cloudformation-validator 2 | this is source code of python script use for validation CF template => more in the blog https://aws.amazon.com/blogs/devops/validating-aws-cloudformation-templates... 3 | 4 | ``` 5 | Usage python cf-validator.py --cf_path CF_Template_File --cf_rules Rules_File --cf_res Resource_File --allow_cap no --region us-east-1 6 | ``` 7 | ### Parameters: 8 | 9 | **--cf_path** [Required]: is the location of CloudFormation template in JSON format. Supported location: 10 | * File system – path to CF template on file sytem 11 | * Web – url to the file on the web e.g. http(s)://my-file.com/my_cf.json 12 | * S3 – path to file in AWS S3 bucket e.g. s3://my_bucket/my_cf.json 13 | 14 | **--cf_rules** [Required]: is the location of JSON file with validation rules. Supporting the same locations like above. See example in cf-rules.json 15 | 16 | **--cf_res** [Optional]: is the location of JSON file with define AWS resources that existence need to be confirm before launch CF template. See example in cf-resources.json 17 | 18 | **--allow_cap** [Optional][yes/no]: this parameter control if you allow create IAM resources such as: policy, rules, IAM user by CF template. Default value is no 19 | 20 | **--region** [Optional]: AWS region where existing resources were created. Default value: us-east-1 21 | -------------------------------------------------------------------------------- /cf-resources.json: -------------------------------------------------------------------------------- 1 | [ 2 | { "Type" : "SG", 3 | "ID" : "sg-37c9b499" 4 | }, 5 | { "Type" : "AMI", 6 | "ID" : "ami-e7e52999" 7 | }, 8 | { "Type" : "Subnet", 9 | "ID" : "subnet-034e2999" 10 | } 11 | ] 12 | -------------------------------------------------------------------------------- /cf-rules.json: -------------------------------------------------------------------------------- 1 | { 2 | "allow_root_keys" : ["AWSTemplateFormatVersion", "Description", "Parameters", "Conditions", "Resources", "Outputs"], 3 | "allow_parameters" : [], 4 | "allow_resources" : [ 5 | "CloudFormation::*", 6 | "CloudWatch::Alarm", 7 | "EC2::Instance", 8 | "EC2::Volume", 9 | "EC2::VolumeAttachment", 10 | "ElasticLoadBalancing::LoadBalancer" 11 | ], 12 | "require_ref_attributes" : 13 | { 14 | "EC2::Instance" : [ "InstanceType", "ImageId", "SecurityGroupIds", "SubnetId", "KeyName", "IamInstanceProfile" ], 15 | "ElasticLoadBalancing::LoadBalancer" : ["SecurityGroups", "Subnets"] 16 | }, 17 | "allow_additional_attributes" : {}, 18 | "not_allow_attributes" : {} 19 | } 20 | -------------------------------------------------------------------------------- /cf-validator.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"). 4 | # You may not use this file except in compliance with the License. 5 | # A copy of the License is located at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # or in the "license" file accompanying this file. This file is distributed 10 | # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | # express or implied. See the License for the specific language governing 12 | # permissions and limitations under the License. 13 | 14 | #!/usr/bin/env python 15 | 16 | from __future__ import print_function 17 | import boto3 18 | import botocore 19 | import time 20 | import sys 21 | import argparse 22 | import json 23 | import urllib2 24 | from pprint import pprint 25 | 26 | aws_profile="" 27 | aws_region="" 28 | 29 | def get_template(template_file): 30 | 31 | ''' 32 | Read a template file and return the contents 33 | ''' 34 | try: 35 | if template_file.startswith("http"): 36 | response = urllib2.urlopen(template_file) 37 | cf_template = response.read() 38 | elif template_file.startswith("s3"): 39 | _, path = (template_file.split("//", 1)) 40 | bucket_name, path = path.split("/", 1) 41 | 42 | global aws_profile 43 | 44 | if aws_profile: 45 | session = boto3.Session(profile_name=aws_profile) 46 | s3 = session.client('s3') 47 | else: 48 | s3 = boto3.client("s3") 49 | 50 | response = s3.get_object(Bucket=bucket_name, Key=path) 51 | cf_template = response['Body'].read() 52 | else: 53 | f = open(template_file, "r") 54 | cf_template = f.read() 55 | except: 56 | print("Error read file: ",template_file) 57 | 58 | return cf_template 59 | 60 | def get_configuration(rules_file): 61 | 62 | ''' 63 | Read a configuration from file or local 64 | ''' 65 | 66 | cf_rules = get_template(rules_file) 67 | j_rules = json.loads(cf_rules) 68 | 69 | allow_root_keys = j_rules["allow_root_keys"] 70 | allow_parameters = j_rules["allow_parameters"] 71 | allow_resources = j_rules["allow_resources"] 72 | require_ref_attributes = j_rules["require_ref_attributes"] 73 | allow_additional_attributes = j_rules["allow_additional_attributes"] 74 | not_allow_attributes = j_rules["not_allow_attributes"] 75 | 76 | return allow_root_keys, allow_parameters, allow_resources, require_ref_attributes, allow_additional_attributes, not_allow_attributes 77 | 78 | def validate_cf_template(cf_template, sc): 79 | 80 | ''' 81 | Validate CF template 82 | ''' 83 | global aws_region 84 | try: 85 | client = boto3.client('cloudformation', region_name=aws_region) 86 | response = client.validate_template(TemplateBody=cf_template) 87 | if ('Capabilities' in response) and (sc == "no"): 88 | print(response['Capabilities'],"=>>", response['CapabilitiesReason']) 89 | return False 90 | else: 91 | return True 92 | except: 93 | print(sys.exc_info()[1]) 94 | return False 95 | 96 | def validate_root_keys(cf_json_keys, valid_root_keys): 97 | 98 | ''' 99 | Validate the root keys of CF template 100 | ''' 101 | 102 | is_valid = False 103 | if not valid_root_keys: 104 | is_valid = True 105 | else: 106 | r = set(cf_json_keys) - set(valid_root_keys) 107 | if not r: 108 | is_valid = True 109 | 110 | return is_valid 111 | 112 | def validate_parameters(cf_parameters, valid_parameters): 113 | 114 | ''' 115 | Validate parameters of in CF template 116 | ''' 117 | 118 | is_valid = False 119 | if not valid_parameters: 120 | is_valid = True 121 | else: 122 | r = set(cf_parameters) - set(valid_parameters) 123 | if not r: 124 | is_valid = True 125 | 126 | return is_valid 127 | 128 | def validate_resources(cf_resources, valid_resources): 129 | 130 | ''' 131 | Validate resources in CF template 132 | ''' 133 | 134 | l_resource = [] 135 | is_valid = False 136 | 137 | for rs in cf_resources.values(): 138 | l_resource.append(rs["Type"].replace('AWS::','')) 139 | 140 | if (not valid_resources) or (not l_resource): 141 | is_valid = True 142 | else: 143 | r_set = set(l_resource) - set(valid_resources) 144 | if not r_set: 145 | is_valid = True 146 | else: 147 | for r in r_set: 148 | if ((r.split("::"))[0])+"::*" not in valid_resources: 149 | return False 150 | is_valid = True 151 | 152 | return is_valid 153 | 154 | def validate_attributes(cf_resources, require_ref_attributes, allow_additional_attributes, not_allow_attributes): 155 | 156 | ''' 157 | Validate attributes of resources in CF template 158 | ''' 159 | 160 | for rs in cf_resources.values(): 161 | rs_type = rs["Type"].replace('AWS::','') 162 | ref_attr = [] 163 | add_attr = [] 164 | not_attr = [] 165 | if rs_type in require_ref_attributes: 166 | ref_attr = require_ref_attributes[rs_type] 167 | if rs_type in allow_additional_attributes: 168 | add_attr = allow_additional_attributes[rs_type] 169 | if rs_type in not_allow_attributes: 170 | not_attr = not_allow_attributes[rs_type] 171 | 172 | if (ref_attr) or (add_attr) or (not_attr): 173 | for atr_key in rs["Properties"].keys(): 174 | if atr_key in not_attr: 175 | print('Not Allow Attribute: ', atr_key) 176 | return False 177 | elif atr_key in ref_attr: 178 | atr_val = rs["Properties"][atr_key] 179 | if isinstance(atr_val, dict) and atr_val.keys()[0] not in 'Ref': 180 | print('Not Refference Attribute: ',atr_key) 181 | return False 182 | elif isinstance(atr_val, list): 183 | for o in atr_val: 184 | if not isinstance(o, dict): 185 | print('Not Refference - too nested: ', atr_key) 186 | return False 187 | elif o.keys()[0] not in 'Ref': 188 | print('Not Refference - sub value:', atr_key) 189 | return False 190 | elif (not isinstance(atr_val, dict)) and (not isinstance(atr_val, list)): 191 | print('Not Refference Attribute: ',atr_key) 192 | return False 193 | elif add_attr and atr_key not in add_attr: 194 | print('Not Allow attribute: ',atr_key) 195 | return False 196 | 197 | return True 198 | 199 | def validate_resources_exist(res_file): 200 | 201 | ''' 202 | Validate if given AWS resource exists and are available 203 | ''' 204 | global aws_profile 205 | global aws_region 206 | is_Valid = True 207 | cf_res = get_template(res_file) 208 | j_res = json.loads(cf_res) 209 | 210 | for r in j_res: 211 | if r["Type"] == "SG": 212 | try: 213 | if aws_profile: 214 | session = boto3.Session(profile_name=aws_profile, region_name=aws_region) 215 | ec2 = session.client('ec2') 216 | else: 217 | ec2 = boto3.resource('ec2', region_name=aws_region) 218 | 219 | sg = ec2.SecurityGroup(r["ID"]).group_name 220 | except: 221 | print(sys.exc_info()[1]) 222 | is_Valid = False 223 | 224 | elif r["Type"] == "AMI": 225 | try: 226 | if aws_profile: 227 | session = boto3.Session(profile_name=aws_profile, region_name=aws_region) 228 | ec2 = session.client('ec2') 229 | else: 230 | ec2 = boto3.resource('ec2', region_name=aws_region) 231 | 232 | state = ec2.Image(r["ID"]).state 233 | if state != "available": 234 | print("AMI Image not available") 235 | is_Valid = False 236 | except: 237 | print(sys.exc_info()[1]) 238 | is_Valid = False 239 | 240 | elif r["Type"] == "Subnet": 241 | try: 242 | if aws_profile: 243 | session = boto3.Session(profile_name=aws_profile, region_name=aws_region) 244 | ec2 = session.client('ec2') 245 | else: 246 | ec2 = boto3.resource('ec2', region_name=aws_region) 247 | 248 | state = ec2.Subnet(r["ID"]).state 249 | if state != "available": 250 | print("Subnet not available") 251 | is_Valid = False 252 | except: 253 | print(sys.exc_info()[1]) 254 | is_Valid = False 255 | 256 | return is_Valid 257 | 258 | def main(arguments): 259 | parser = argparse.ArgumentParser( 260 | description=__doc__, 261 | formatter_class=argparse.RawDescriptionHelpFormatter) 262 | parser.add_argument('--cf_path', required=True) 263 | parser.add_argument('--cf_rules', required=True) 264 | parser.add_argument('--cf_res',default='') 265 | parser.add_argument('--allow_cap',default='no') 266 | parser.add_argument('--region',default='us-east-1') 267 | parser.add_argument('--aws_profile',default='') 268 | args = parser.parse_args(arguments) 269 | 270 | global aws_profile 271 | aws_profile = args.aws_profile 272 | 273 | global aws_region 274 | aws_region = args.region 275 | 276 | cf_template = get_template(args.cf_path) 277 | try: 278 | j_cf = json.loads(cf_template) 279 | except: 280 | sys.exit("CF Template - not valid json format") 281 | 282 | if not validate_cf_template(cf_template, args.allow_cap): 283 | sys.exit("CF Template not valid") 284 | 285 | allow_root_keys, allow_parameters, allow_resources, require_ref_attributes, allow_additional_attributes, not_allow_attributes = get_configuration(args.cf_rules) 286 | 287 | if not validate_root_keys(j_cf.keys(),allow_root_keys): 288 | sys.exit("Root Tags are not valid") 289 | 290 | if not validate_parameters(j_cf["Parameters"].keys(),allow_parameters): 291 | sys.exit("Parameters are not valid") 292 | 293 | if not validate_resources(j_cf["Resources"],allow_resources): 294 | sys.exit("Resources are not valid") 295 | 296 | if not validate_attributes(j_cf["Resources"],require_ref_attributes, allow_additional_attributes, not_allow_attributes): 297 | sys.exit("Require Resources are not valid") 298 | 299 | if args.cf_res: 300 | if not validate_resources_exist(args.cf_res): 301 | sys.exit("Resources not found") 302 | 303 | print("CloudFormation Template Valid") 304 | 305 | if __name__ == '__main__': 306 | sys.exit(main(sys.argv[1:])) 307 | --------------------------------------------------------------------------------