cloudformation-dsl 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 21385e1f3497de9e3748bc0ccbdbcb39b63949c2
4
+ data.tar.gz: 9681b47166cac0221e60c372899ad5ded79e8da6
5
+ SHA512:
6
+ metadata.gz: 78e4b1e92f609e4275ec4bcd869f4cd86d6ae2278f9acc2747390d70f4123c6a542e5259c453d0cd7954adfd3aadc6322545aee47e2fa4f3212005a5484695f7
7
+ data.tar.gz: 58c23d4b9e2de160d50dfb1a794b43929fb0e71c17106a590bc32fd5119eb478c8efed778212cf5c825d847e7a60e12c0537e82d160ab9a80d54f1870d80eb90
data/.gitignore ADDED
@@ -0,0 +1,29 @@
1
+ *.swp
2
+ maestro.json
3
+ .rakeTasks
4
+ .DS_Store
5
+ target
6
+ *.iml
7
+ .idea/
8
+ *.swo
9
+ /manifests
10
+ /modules
11
+ cloudformation/expanded/
12
+ *.gem
13
+ *.rbc
14
+ .bundle
15
+ .config
16
+ .yardoc
17
+ Gemfile.lock
18
+ InstalledFiles
19
+ _yardoc
20
+ coverage
21
+ doc/
22
+ lib/bundler/man
23
+ pkg
24
+ rdoc
25
+ spec/reports
26
+ test/tmp
27
+ test/version_tmp
28
+ tmp
29
+ .rvmrc
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in cloudformation-ruby-dsl.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
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 2014 Bazaarvoice
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.
data/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # cloudformation-ruby-dsl
2
+
3
+ A Ruby DSL and helper utilities for building CloudFormation templates dynamically.
4
+
5
+ This is a fork of bazzarvoice/cloudformation-ruby-dsl. However, that gem does more than simply being a DSL. This fork cuts out the non-DSL
6
+ feature. It provides:
7
+
8
+ - Ruby DSL to generate a CloudFormation template described in JSON
9
+ - A conversion tool
10
+
11
+ To upload the template, you use other tools such as the AWS Ruby SDK or Fog/AWS.
12
+
13
+ Original credits: Written by [Bazaarvoice](http://www.bazaarvoice.com): see [the contributors page](https://github.com/bazaarvoice/cloudformation-ruby-dsl/graphs/contributors) and [the initial contributions](https://github.com/bazaarvoice/cloudformation-ruby-dsl/blob/master/initial_contributions.md) for more details.
14
+
15
+ ## Motivation
16
+
17
+ CloudFormation templates often contain repeated stanzas, information which must be loaded from external sources, and other functionality that would be easier handled as code, instead of configuration.
18
+
19
+ Consider when a userdata script needs to be added to a CloudFormation template. Traditionally, you would re-write the script by hand in a valid JSON format. Using the DSL, you can specify the file containing the script and generate the correct information at runtime.
20
+
21
+ :UserData => base64(interpolate(file('userdata.sh')))
22
+
23
+ Additionally, CloudFormation templates are just massive JSON documents, making general readability and reusability an issue. The DSL allows not only a cleaner format (and comments!), but will also allow the same DSL template to be reused as needed.
24
+
25
+ ## Installation
26
+
27
+ Run `gem install cloudformation-dsl` to install system-wide.
28
+
29
+ To use in a specific project, add `gem 'cloudformation-dsl'` to your Gemfile, and then run `bundle`.
30
+
31
+ ## Releasing
32
+
33
+ See [Releasing](docs/Releasing.md).
34
+
35
+ ## Contributing
36
+
37
+ See [Contributing](docs/Contributing.md).
38
+
39
+ ## Usage
40
+
41
+ To convert existing JSON templates to use the DSL, run
42
+
43
+ cfntemplate-to-ruby [EXISTING_CFN] > [NEW_NAME.rb]
44
+
45
+ You may need to preface this with `bundle exec` if you installed via Bundler.
46
+
47
+ Below are the various functions currently available in the DSL. See [the example script](examples/cloudformation-ruby-script.rb) for more usage information.
48
+
49
+ ### DSL Statements
50
+
51
+ Everything should be wrapped in the following:
52
+
53
+ ```
54
+ template = CloudFormationDSL.describe do
55
+ # ... statements ...
56
+ end
57
+ ```
58
+
59
+ Once there, you can get the JSON by calling `template.to_json`.
60
+
61
+ Add the named object to the appropriate collection.
62
+ - `parameter(name, options)` (may be marked :Immutable, which will raise error on a later change)
63
+ - `mapping(name, options)`
64
+ - `condition(name, conditions)`
65
+ - `resource(name, options)`
66
+ - `output(name, options)`
67
+
68
+ ### CloudFormation Function Calls
69
+
70
+ Invoke an intrinsic CloudFormation function.
71
+ - `base64(value)`
72
+ - `find_in_map(map, key, name)`
73
+ - `get_att(resource, attribute)`
74
+ - `get_azs(region)`
75
+ - `join(delim, *list)`
76
+ - `select(index, list)`
77
+ - `ref(name)`
78
+
79
+ Intrinsic conditionals are also supported, with some syntactic sugar.
80
+ - `fn_not(condition)`
81
+ - `fn_or(*condition_list)`
82
+ - `fn_and(*condition_list)`
83
+ - `fn_if(condition, value_if_true, value_if_false)`
84
+ - `equal(lhsOperand, rhsOperand)`
85
+ - `not_equal(lhsOperand, rhsOperand)`
86
+
87
+ Reference a CloudFormation pseudo parameter.
88
+ - `aws_account_id()`
89
+ - `aws_notification_arns()`
90
+ - `aws_no_value()`
91
+ - `aws_region()`
92
+ - `aws_stack_id()`
93
+ - `aws_stack_name()`
94
+
95
+ ### Utility Functions
96
+
97
+ Additional capabilities for file inclusion, etc.
98
+ - `tag(tag)`: add tags to the stack, which are inherited by all resources in that stack; can only be used at launch
99
+ - `file(name)`: return the named file as a string, for further use
100
+ - `load_from_file(filename)`: load the named file by a given type; currently handles YAML, JSON, and Ruby
101
+ - `interpolate(string)`: embed CFN references into a string (`{{ref('Service')}}`) for later interpretation by the CFN engine
102
+ - `Table.load(filename)`: load a table from the listed file, which can then be turned into mappings (via `get_map`)
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
@@ -0,0 +1,345 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ # Copyright 2013-2014 Bazaarvoice, Inc.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ unless RUBY_VERSION >= '1.9'
18
+ # Ruby 1.9 preserves order within Hash objects which avoid scrambling the template output.
19
+ $stderr.puts "This script requires ruby 1.9+. On OS/X use Homebrew to install ruby 1.9:"
20
+ $stderr.puts " brew install ruby"
21
+ exit(2)
22
+ end
23
+
24
+ require 'json'
25
+
26
+ def main(argv)
27
+ unless (argv & %w(-h --help -?)).empty?
28
+ $stderr.puts <<"EOF"
29
+ usage: #{$PROGRAM_NAME} [cloudformation-template.json] ...
30
+
31
+ Converts the specified CloudFormation JSON template or template fragment to
32
+ Ruby DSL syntax. Reads from stdin or from the specified json files. Note
33
+ that the input must be valid JSON.
34
+
35
+ Examples:
36
+
37
+ # Convert a JSON CloudFormation template to Ruby DSL syntax
38
+ #{$PROGRAM_NAME} my-template.json > my-template.rb
39
+ chmod +x my-template.rb
40
+
41
+ # Convert the JSON fragment in the clipboard to Ruby DSL syntax
42
+ pbpaste | #{$PROGRAM_NAME} | less
43
+
44
+ EOF
45
+ exit(2)
46
+ end
47
+ if argv.empty?
48
+ pprint(simplify(JSON.parse($stdin.read)))
49
+ else
50
+ argv.each do |filename|
51
+ pprint(simplify(JSON.parse(File.read(filename))))
52
+ end
53
+ end
54
+ # The user should make the resulting template executable w/chmod +x
55
+ end
56
+
57
+ class FnCall
58
+ attr_reader :name, :arguments, :multiline
59
+
60
+ def initialize(name, arguments, multiline = false)
61
+ @name = name
62
+ @arguments = arguments
63
+ @multiline = multiline
64
+ end
65
+
66
+ def to_s()
67
+ @name + "(" + @arguments.join(', ') + ")"
68
+ end
69
+ end
70
+
71
+ def pprint(val)
72
+ case detect_type(val)
73
+ when :template
74
+ pprint_cfn_template(val)
75
+ when :parameter
76
+ pprint_cfn_section 'parameter', 'TODO', val
77
+ when :resource
78
+ pprint_cfn_resource 'TODO', val
79
+ when :parameters
80
+ val.each { |k, v| pprint_cfn_section 'parameter', k, v }
81
+ when :resources
82
+ val.each { |k, v| pprint_cfn_resource k, v }
83
+ else
84
+ pprint_value(val, '')
85
+ end
86
+ end
87
+
88
+ # Attempt to figure out what fragment of the template we have. This is imprecise and can't
89
+ # detect Mappings and Outputs sections reliably, so it doesn't attempt to.
90
+ def detect_type(val)
91
+ if val.is_a?(Hash) && val['AWSTemplateFormatVersion']
92
+ :template
93
+ elsif val.is_a?(Hash) && /^(String|Number)$/ =~ val['Type']
94
+ :parameter
95
+ elsif val.is_a?(Hash) && val['Type']
96
+ :resource
97
+ elsif val.is_a?(Hash) && val.values.all? { |v| detect_type(v) == :parameter }
98
+ :parameters
99
+ elsif val.is_a?(Hash) && val.values.all? { |v| detect_type(v) == :resource }
100
+ :resources
101
+ end
102
+ end
103
+
104
+ def pprint_cfn_template(tpl)
105
+ puts "#!/usr/bin/env ruby"
106
+ puts
107
+ puts "require 'bundler/setup'"
108
+ puts "require 'cloudformation-ruby-dsl/cfntemplate'"
109
+ puts "require 'cloudformation-ruby-dsl/spotprice'"
110
+ puts "require 'cloudformation-ruby-dsl/table'"
111
+ puts
112
+ puts "template do"
113
+ puts
114
+ tpl.each do |section, v|
115
+ case section
116
+ when 'Parameters'
117
+ v.each { |name, options| pprint_cfn_section 'parameter', name, options }
118
+ when 'Mappings'
119
+ v.each { |name, options| pprint_cfn_section 'mapping', name, options }
120
+ when 'Resources'
121
+ v.each { |name, options| pprint_cfn_resource name, options }
122
+ when 'Conditions'
123
+ v.each { |name, options| pprint_cfn_section 'condition', name, options }
124
+ when 'Outputs'
125
+ v.each { |name, options| pprint_cfn_section 'output', name, options }
126
+ else
127
+ print " value #{fmt_key(section)} => "
128
+ pprint_value v, ' '
129
+ puts
130
+ puts
131
+ end
132
+ end
133
+ puts "end.exec!"
134
+ end
135
+
136
+ def pprint_cfn_section(section, name, options)
137
+ print " #{section} #{fmt_string(name)}"
138
+ indent = ' ' + (' ' * section.length) + ' '
139
+ options.each do |k, v|
140
+ puts ","
141
+ print indent, fmt_key(k), " => "
142
+ pprint_value v, indent
143
+ end
144
+ puts
145
+ puts
146
+ end
147
+
148
+ def pprint_cfn_resource(name, options)
149
+ print " resource #{fmt_string(name)}"
150
+ indent = ' '
151
+ options.each do |k, v|
152
+ unless k == 'Properties'
153
+ print ", #{fmt_key(k)} => #{fmt(v)}"
154
+ end
155
+ end
156
+ if options.key?('Properties')
157
+ print ", #{fmt_key('Properties')} => "
158
+ pprint_value options['Properties'], indent
159
+ end
160
+ puts
161
+ puts
162
+ end
163
+
164
+ def pprint_value(val, indent)
165
+ # Prefer to print the value on a single line if it's reasonable to do so
166
+ single_line = is_single_line(val) || is_single_line_hack(val)
167
+ if single_line && !is_multi_line_hack(val)
168
+ s = fmt(val)
169
+ if s.length < 120 || is_single_line_hack(val)
170
+ print s
171
+ return
172
+ end
173
+ end
174
+
175
+ # Print the value across multiple lines
176
+ if val.is_a?(Hash)
177
+ puts "{"
178
+ val.each do |k, v|
179
+ print "#{indent} #{fmt_key(k)} => "
180
+ pprint_value v, indent + ' '
181
+ puts ","
182
+ end
183
+ print "#{indent}}"
184
+
185
+ elsif val.is_a?(Array)
186
+ puts "["
187
+ val.each do |v|
188
+ print "#{indent} "
189
+ pprint_value v, indent + ' '
190
+ puts ","
191
+ end
192
+ print "#{indent}]"
193
+
194
+ elsif val.is_a?(FnCall) && val.multiline
195
+ print val.name, "("
196
+ args = val.arguments
197
+ sep = ''
198
+ sub_indent = indent + ' '
199
+ if val.name == 'join' && args.length > 1
200
+ pprint_value args[0], indent + ' '
201
+ args = args[1..-1]
202
+ sep = ','
203
+ sub_indent = indent + ' '
204
+ end
205
+ unless args.empty?
206
+ args.each do |v|
207
+ puts sep
208
+ print sub_indent
209
+ pprint_value v, sub_indent
210
+ sep = ','
211
+ end
212
+ if val.name == 'join' && args.length > 1
213
+ print ","
214
+ end
215
+ puts
216
+ print indent
217
+ end
218
+ print ")"
219
+
220
+ else
221
+ print fmt(val)
222
+ end
223
+ end
224
+
225
+ def is_single_line(val)
226
+ if val.is_a?(Hash)
227
+ is_single_line(val.values)
228
+ elsif val.is_a?(Array)
229
+ val.empty? ||
230
+ (val.length == 1 && is_single_line(val[0]) && !val[0].is_a?(Hash)) ||
231
+ val.all? { |v| v.is_a?(String) }
232
+ else
233
+ true
234
+ end
235
+ end
236
+
237
+ # Emo-specific hacks to force the desired output formatting
238
+ def is_single_line_hack(val)
239
+ is_array_of_strings_hack(val)
240
+ end
241
+
242
+ # Emo-specific hacks to force the desired output formatting
243
+ def is_multi_line_hack(val)
244
+ val.is_a?(Hash) && val['email']
245
+ end
246
+
247
+ # Emo-specific hacks to force the desired output formatting
248
+ def is_array_of_strings_hack(val)
249
+ val.is_a?(Array) && val.all? { |v| v.is_a?(String) } && val.grep(/\s/).empty? && (
250
+ val.include?('autoscaling:EC2_INSTANCE_LAUNCH') ||
251
+ val.include?('m1.small')
252
+ )
253
+ end
254
+
255
+ def fmt(val)
256
+ if val == {}
257
+ '{}'
258
+ elsif val == []
259
+ '[]'
260
+ elsif val.is_a?(Hash)
261
+ '{ ' + (val.map { |k,v| fmt_key(k) + ' => ' + fmt(v) }).join(', ') + ' }'
262
+ elsif val.is_a?(Array) && is_array_of_strings_hack(val)
263
+ '%w(' + val.join(' ') + ')'
264
+ elsif val.is_a?(Array)
265
+ '[ ' + (val.map { |v| fmt(v) }).join(', ') + ' ]'
266
+ elsif val.is_a?(FnCall) && val.arguments.empty?
267
+ val.name
268
+ elsif val.is_a?(FnCall)
269
+ val.name + '(' + (val.arguments.map { |v| fmt(v) }).join(', ') + ')'
270
+ elsif val.is_a?(String)
271
+ fmt_string(val)
272
+ elsif val == nil
273
+ 'null'
274
+ else
275
+ val.to_s # number, boolean
276
+ end
277
+ end
278
+
279
+ def fmt_key(s)
280
+ ':' + (/^[a-zA-Z_]\w+$/ =~ s ? s : fmt_string(s)) # returns a symbol like :Foo or :'us-east-1'
281
+ end
282
+
283
+ def fmt_string(s)
284
+ if /[^ -~]/ =~ s
285
+ s.dump # contains, non-ascii or control char, return double-quoted string
286
+ else
287
+ '\'' + s.gsub(/([\\'])/, '\\\\\1') + '\'' # return single-quoted string, escape \ and '
288
+ end
289
+ end
290
+
291
+ def many(val)
292
+ if val.is_a?(Array)
293
+ val
294
+ else
295
+ [ val ]
296
+ end
297
+ end
298
+
299
+ def simplify(val)
300
+ if val.is_a?(Hash)
301
+ val = Hash[val.map { |k,v| [k, simplify(v)] }]
302
+ if val.length != 1
303
+ val
304
+ else
305
+ k, v = val.entries[0]
306
+ # CloudFormation functions
307
+ case
308
+ when k == 'Fn::Base64'
309
+ FnCall.new 'base64', [v], true
310
+ when k == 'Fn::FindInMap'
311
+ FnCall.new 'find_in_map', v
312
+ when k == 'Fn::GetAtt'
313
+ FnCall.new 'get_att', v
314
+ when k == 'Fn::GetAZs'
315
+ FnCall.new 'get_azs', v != '' ? [v] : []
316
+ when k == 'Fn::Join'
317
+ FnCall.new 'join', [v[0]] + many(v[1]), true
318
+ when k == 'Fn::Select'
319
+ FnCall.new 'select', v
320
+ when k == 'Ref' && v == 'AWS::AccountId'
321
+ FnCall.new 'aws_account_id', []
322
+ when k == 'Ref' && v == 'AWS::NotificationARNs'
323
+ FnCall.new 'aws_notification_arns', []
324
+ when k == 'Ref' && v == 'AWS::NoValue'
325
+ FnCall.new 'aws_no_value', []
326
+ when k == 'Ref' && v == 'AWS::Region'
327
+ FnCall.new 'aws_region', []
328
+ when k == 'Ref' && v == 'AWS::StackId'
329
+ FnCall.new 'aws_stack_id', []
330
+ when k == 'Ref' && v == 'AWS::StackName'
331
+ FnCall.new 'aws_stack_name', []
332
+ when k == 'Ref'
333
+ FnCall.new 'ref', [v]
334
+ else
335
+ val
336
+ end
337
+ end
338
+ elsif val.is_a?(Array)
339
+ val.map { |v| simplify(v) }
340
+ else
341
+ val
342
+ end
343
+ end
344
+
345
+ main(ARGV)