Module: Sfn::CommandModule::Stack::InstanceMethods

Defined in:
lib/sfn/command_module/stack.rb

Constant Summary collapse

MAX_PARAMETER_ATTEMPTS =

maximum number of attempts to get valid parameter value

5
TEMPLATE_PARAMETER_LOCATIONS =

Template parameter locations

['Parameters', 'parameters']
TEMPLATE_PARAMETER_DEFAULTS =

Template parameter default value locations

['Default', 'defaultValue', 'default']

Instance Method Summary collapse

Instance Method Details

#apply_nested_stacks!(remote_stack, stack) ⇒ Miasma::Models::Orchestration::Stack

Detect nested stacks and apply

Parameters:

  • remote_stack (Miasma::Models::Orchestration::Stack)

    stack to inspect for nested stacks

  • stack (Miasma::Models::Orchestration::Stack)

    current stack

Returns:

  • (Miasma::Models::Orchestration::Stack)


43
44
45
46
47
48
49
50
51
52
53
# File 'lib/sfn/command_module/stack.rb', line 43

def apply_nested_stacks!(remote_stack, stack)
  remote_stack.resources.all.each do |resource|
    if(valid_stack_types.include?(resource.type))
      nested_stack = resource.expand
      apply_nested_stacks!(nested_stack, stack)
      mappings = generate_custom_apply_mappings(nested_stack)
      execute_apply_stack(nested_stack, stack, mappings)
    end
  end
  stack
end

#apply_stacks!(stack) ⇒ Miasma::Models::Orchestration::Stack

Apply any defined remote stacks

Parameters:

  • stack (Miasma::Models::Orchestration::Stack)

Returns:

  • (Miasma::Models::Orchestration::Stack)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/sfn/command_module/stack.rb', line 22

def apply_stacks!(stack)
  remote_stacks = [config[:apply_stack]].flatten.compact
  remote_stacks.each do |stack_name|
    remote_stack = provider.stack(stack_name)
    if(remote_stack)
      apply_nested_stacks!(remote_stack, stack)
      mappings = generate_custom_apply_mappings(remote_stack)
      execute_apply_stack(remote_stack, stack, mappings)
    else
      ui.error "Failed to apply requested stack. Unable to locate. (#{stack_name})"
      raise "Failed to locate stack: #{stack}"
    end
  end
  stack
end

#config_root_parametersHash

Returns parameters for root stack create/update.

Returns:

  • (Hash)

    parameters for root stack create/update



207
208
209
210
211
212
213
# File 'lib/sfn/command_module/stack.rb', line 207

def config_root_parameters
  Hash[
    config.fetch(:parameters, {}).find_all do |k,v|
      !k.include?('__')
    end
  ]
end

#execute_apply_stack(provider_stack, receiver_stack, mappings) ⇒ TrueClass

Apply provider stack outputs to receiver stack parameters

Parameters:

  • provider_stack (Miasma::Models::Orchestration::Stack)

    stack providing outputs

  • receiver_stack (Miasma::Models::Orchestration::Stack)

    stack receiving outputs for parameters

Returns:

  • (TrueClass)


84
85
86
87
# File 'lib/sfn/command_module/stack.rb', line 84

def execute_apply_stack(provider_stack, receiver_stack, mappings)
  receiver_stack.apply_stack(provider_stack, :mapping => mappings)
  true
end

#function_set_parameter?(val) ⇒ TrueClass, FalseClass

Determine if parameter was set via intrinsic function

Parameters:

  • val (Object)

Returns:

  • (TrueClass, FalseClass)


202
203
204
# File 'lib/sfn/command_module/stack.rb', line 202

def function_set_parameter?(val)
  val.is_a?(Hash)
end

#generate_custom_apply_mappings(provider_stack) ⇒ Hash

Build apply mappings valid for given provider stack

Parameters:

  • provider_stack (Miasma::Models::Orchestration::Stack)

    stack providing outputs

Returns:

  • (Hash)

    output to parameter mapping



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/sfn/command_module/stack.rb', line 59

def generate_custom_apply_mappings(provider_stack)
  if(config[:apply_mapping])
    valid_keys = config[:apply_mapping].keys.find_all do |a_key|
      a_key = a_key.to_s
      !a_key.include?('__') ||
        a_key.split('__').first == provider_stack.name
    end
    to_remove = valid_keys.find_all do |key|
      valid_keys.any?{|v_key| v_key.match(/__#{Regexp.escape(key)}$/)}
    end
    valid_keys -= to_remove
    Hash[
      valid_keys.map do |a_key|
        cut_key = a_key.include?('__') ? a_key.slice(a_key.index('__') + 2, a_key.length) : a_key
        [cut_key, config[:apply_mapping][a_key]]
      end
    ]
  end
end

#populate_parameters!(sparkle, opts = {}) ⇒ Hash

Prompt for parameter values and store result

Parameters:

  • sparkle (SparkleFormation, Hash)
  • opts (Hash) (defaults to: {})

Options Hash (opts):

  • :current_parameters (Hash)

    current stack parameter values

  • :stack (Miasma::Models::Orchestration::Stack)

    existing stack

Returns:

  • (Hash)


96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/sfn/command_module/stack.rb', line 96

def populate_parameters!(sparkle, opts={})
  current_parameters = opts.fetch(:current_parameters, {})
  current_stack = opts[:stack]
  if(sparkle.is_a?(SparkleFormation))
    parameter_prefix = sparkle.root? ? [] : (sparkle.root_path - [sparkle.root]).map do |s|
      Bogo::Utility.camel(s.name)
    end
    stack_parameters = sparkle.compile.parameters
    stack_parameters = stack_parameters.nil? ? Smash.new : stack_parameters._dump
  else
    parameter_prefix = []
    stack_parameters = TEMPLATE_PARAMETER_LOCATIONS.map do |loc_key|
      sparkle[loc_key]
    end.compact.first || Smash.new
  end
  unless(stack_parameters.empty?)
    if(config.get(:parameter).is_a?(Array))
      config[:parameter] = Smash[
        *config.get(:parameter).map(&:to_a).flatten
      ]
    end
    if(config.get(:parameters))
      config.set(:parameters,
        config.get(:parameters).merge(config.fetch(:parameter, Smash.new))
      )
    else
      config.set(:parameters, config.fetch(:parameter, Smash.new))
    end
    param_banner = false
    stack_parameters.each do |k,v|
      ns_k = (parameter_prefix + [k]).compact.join('__')
      next if config[:parameters][ns_k]
      valid = false
      # When parameter is a hash type, it is being set via
      # intrinsic function and we don't modify
      if(function_set_parameter?(current_parameters[k]))
        if(current_stack)
          enable_set = validate_stack_parameter(current_stack, k, ns_k, current_parameters[k])
        else
          enable_set = true
        end
        if(enable_set)
          # NOTE: direct set dumps the stack (nfi). Smash will
          # auto dup it, and works, so yay i guess.
          config[:parameters][ns_k] = current_parameters[k].is_a?(Hash) ? Smash.new(current_parameters[k]) : current_parameters[k].dup
          valid = true
        end
      else
        if(current_stack && current_stack.data[:parent_stack])
          use_expected = validate_stack_parameter(current_stack, k, ns_k, current_parameters[k])
          unless(use_expected)
            current_parameters[k] = current_stack.parameters[k]
          end
        end
      end
      attempt = 0
      if(!valid && !param_banner)
        if(sparkle.is_a?(SparkleFormation))
          ui.info "#{ui.color('Stack runtime parameters:', :bold)} - template: #{ui.color(sparkle.root_path.map(&:name).map(&:to_s).join(' > '), :green, :bold)}"
        else
          ui.info ui.color('Stack runtime parameters:', :bold)
        end
        param_banner = true
      end
      until(valid)
        attempt += 1
        default = config[:parameters].fetch(
          ns_k, current_parameters.fetch(
            k, TEMPLATE_PARAMETER_DEFAULTS.map{|loc_key| v[loc_key]}.compact.first
          )
        )
        if(config[:interactive_parameters])
          answer = ui.ask_question("#{k.split(/([A-Z]+[^A-Z]*)/).find_all{|s|!s.empty?}.join(' ')}", :default => default)
        else
          answer = default
        end
        validation = validate_parameter(answer, v)
        if(validation == true)
          config[:parameters][ns_k] = answer
          valid = true
        else
          validation.each do |validation_error|
            ui.error validation_error.last
          end
        end
        if(attempt > MAX_PARAMETER_ATTEMPTS)
          ui.fatal 'Failed to receive allowed parameter!'
          exit 1
        end
      end
    end
  end
  Smash[
    config.fetch(:parameters, {}).map do |k,v|
      strip_key = parameter_prefix ? k.sub(/#{parameter_prefix.join('__')}_{2}?/, '') : k
      unless(strip_key.include?('__'))
        [strip_key, v]
      end
    end.compact
  ]
end

#validate_stack_parameter(c_stack, p_key, p_ns_key, c_value) ⇒ TrueClass, FalseClass

Validate stack parameter is properly set via stack resource from parent stack. If not properly set, prompt user for expected behavior. This accounts for states encountered when a nested stack’s parameters are adjusted directly but the resource sets value via intrinsic function.

Parameters:

  • c_stack (Miasma::Models::Orchestration::Stack)

    current stack

  • p_key (String)

    stack parameter key

  • p_ns_key (String)

    namespaced stack parameter key

  • c_value (Hash)

    currently set value (via intrinsic function)

Returns:

  • (TrueClass, FalseClass)

    value is validated



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/sfn/command_module/stack.rb', line 226

def validate_stack_parameter(c_stack, p_key, p_ns_key, c_value)
  stack_value = c_stack.parameters[p_key]
  p_stack = c_stack.data[:parent_stack]
  if(c_value.is_a?(Hash))
    case c_value.keys.first
    when 'Ref'
      current_value = p_stack.parameters[c_value.values.first]
    when 'Fn::Att'
      resource_name, output_name = c_value.values.first.split('.', 2)
      ref_stack = p_stack.nested_stacks.detect{|i| i.data[:logical_id] == resource_name}
      if(ref_stack)
        output = ref_stack.outputs.detect do |o|
          o.key == output_name
        end
        if(output)
          current_value = output.value
        end
      end
    end
  else
    current_value = c_value
  end
  if(current_value && current_value.to_s != stack_value.to_s)
    ui.warn 'Nested stack has been altered directly! This update may cause unexpected modifications!'
    ui.warn "Stack name: #{c_stack.name}. Parameter: #{p_key}. Current value: #{stack_value}. Expected value: #{current_value} (via: #{c_value.inspect})"
    answer = ui.ask_question("Use current value or expected value for #{p_key} [current/expected]?", :valid => ['current', 'expected'])
    answer == 'expected'
  else
#            ui.warn "Unable to check #{p_key} for direct value modification. (Cannot auto-check expected value #{c_value.inspect})"
    true
  end
end