class Object
Constants
- API_GATEWAY_CLOUDWATCH_LOGS
- AWS_REGION
- COGNITO_AUTH_ROLE
AWS IAM Roles
- COGNITO_UNAUTH_ROLE
- DATADOG_ACCOUNT_ID
- DATADOG_ROLE
- DEFAULT_MAINTENANCE_TIME
- DEFAULT_SNAPSHOT_NUM
- DEFAULT_SNAPSHOT_TIME
- DOMAIN
AWS Constants
- EC2_DEFAULT_IMAGE
- EC2_DEFAULT_INSTANCE_TYPE
- EC2_INSTANCE_TYPES
- ECS_INSTANCE_ROLE
- ECS_SERVICE_ROLE
- ELASTICACHE_DEFAULT_ENGINE
- ELASTICACHE_DEFAULT_ENGINE_VERSION
aws –region <REGION> elasticache describe-cache-engine-versions \
| jq -r '.CacheEngineVersions[] | select(.Engine == "<ENGINE>") | .EngineVersion'
- ELASTICACHE_DEFAULT_NODE_TYPE
- ELASTICACHE_NODE_TYPES
- ELASTIC_BEANTALK_EC2_DEFAULT_ROLE
- ELASTIC_BEANTALK_LINUX
docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.platforms.html
- ELASTIC_BEANTALK_PLATFORM
- ELB_ACCESS_LOG_ACCOUNT_ID
- EMR_DEFAULT_INSTANCE_TYPE
- EMR_DEFAULT_RELEASE
docs.aws.amazon.com/ElasticMapReduce/latest/ReleaseGuide/emr-whatsnew.html
- EMR_INSTANCE_TYPES
- KINESIS_FIREHOSE_DELIVERY_STREAM_ROLE
- KUMOGATA_TEMPLATE_VERSION
- PINPOINT_ADMIN_ROLE
- PINPOINT_KINESIS_FIREHOSE_DELIVERY_STREAM_ROLE
- PINPOINT_KINESIS_STREAM_ROLE
- PORT
- RDS_AURORA_DEFAULT_INSTANCE_CLASS
- RDS_AURORA_INSTANCE_CLASSES
- RDS_DEFAULT_CLUSTER_ENGINE
- RDS_DEFAULT_ENGINE
- RDS_DEFAULT_ENGINE_VERSION
aws –region <REGION> rds describe-db-engine-versions –query “DBEngineVersions[] | [?Engine == 'mysql'].EngineVersion”
- RDS_DEFAULT_INSTANCE_CLASS
- RDS_INSTANCE_CLASSES
- REDSHIFT_DEFAULT_NODE_TYPE
- REDSHIFT_NODE_TYPES
- SSM_INSTANCE_ROLE
Public Instance Methods
_account_id()
click to toggle source
# File lib/kumogata/template/helper.rb, line 327 def _account_id _ref_pseudo("account id") end
_alb_actions(args)
click to toggle source
# File lib/kumogata/template/alb.rb, line 71 def _alb_actions(args) (args[:actions] || []).collect do |default| target = _ref_string("target", default, "target group") _{ TargetGroupArn target Type "forward" } end end
_alb_attributes(args)
click to toggle source
# File lib/kumogata/template/alb.rb, line 91 def _alb_attributes(args) (args[:attributes] || []).collect do |attribute| type = attribute[:type] || '' case type when 'log' attribute = _alb_to_lb_attribute_access_log(attribute) when 'timeout' attribute = _alb_to_lb_attribute_idle_timeout(attribute[:timeout]) when 'delay-timeout' attribute = _alb_to_target_group_attribute_delay_timeout(attribute[:timeout]) end _pair_value({ attribute: attribute }, 'attribute') end.flatten end
_alb_certificates(args)
click to toggle source
# File lib/kumogata/template/alb.rb, line 61 def _alb_certificates(args) certificate = _ref_string("certificate", args) [ _{ CertificateArn certificate } ] end
_alb_conditions(args)
click to toggle source
# File lib/kumogata/template/alb.rb, line 81 def _alb_conditions(args) (args[:conditions] || []).collect do |condition| condition = [ condition ] unless condition.is_a? Array _{ Field "path-pattern" Values condition } end end
_alb_health_check(args)
click to toggle source
# File lib/kumogata/template/alb.rb, line 116 def _alb_health_check(args) type = args[:type] || '' case type when 'min' return _alb_to_min_health_check(args) end protocol = _valid_values(args[:protocol] || "", %w( http https ), "http") # return to native hash { interval: args[:interval] || 30, path: args[:path] || "/", port: args[:port] || 80, protocol: protocol.upcase, timeout: args[:timeout] || 5, healthy: args[:healthy] || 10, unhealthly: args[:unhealthly] || 2, } end
_alb_matcher(args)
click to toggle source
# File lib/kumogata/template/alb.rb, line 107 def _alb_matcher(args) args[:matcher] = 200 unless args.key? :matcher http_code = _valid_values(args[:matcher], %w( 200 202 299 ), 200) _{ HttpCode http_code } end
_alb_targets(args)
click to toggle source
# File lib/kumogata/template/alb.rb, line 137 def _alb_targets(args) targets = (args[:targets] || []).collect do |target| id = _ref_string("instance", target, "instance") _{ Id id Port target[:port] if target.key? :port } end targets += (args[:ref_targets] || []).collect do |target| _{ Id _ref_string("instance", { ref_instance: target }, "instance") Port 80 } end targets end
_alb_to_lb_attribute_access_log(args)
click to toggle source
# File lib/kumogata/template/alb.rb, line 6 def _alb_to_lb_attribute_access_log(args) { "access_logs.s3.enabled": true, "access_logs.s3.bucket": args[:bucket], "access_logs.s3.prefix": args[:prefix], } end
_alb_to_lb_attribute_delete_protection()
click to toggle source
# File lib/kumogata/template/alb.rb, line 14 def _alb_to_lb_attribute_delete_protection { "deletion_protection.enabled": true } end
_alb_to_lb_attribute_idle_timeout(value)
click to toggle source
# File lib/kumogata/template/alb.rb, line 20 def _alb_to_lb_attribute_idle_timeout(value) # idle timeout seconds 1-3600 { "idle_timeout.timeout_seconds": value } end
_alb_to_lb_http2(value = true)
click to toggle source
# File lib/kumogata/template/alb.rb, line 27 def _alb_to_lb_http2(value = true) { "routing.http2.enabled": value } end
_alb_to_min_health_check(args)
click to toggle source
# File lib/kumogata/template/alb.rb, line 49 def _alb_to_min_health_check(args) { protocol: _valid_values(args[:protocol], %w( http https ), 'http').upcase, path: args[:path] || '/', port: args[:port] || 80, healthy: args[:healthy] || 2, unhealthly: args[:unhealthly] || 2, timeout: args[:timeout] || 2, interval: args[:interval] || 5, } end
_alb_to_target_group_attribute_delay_timeout(value)
click to toggle source
# File lib/kumogata/template/alb.rb, line 33 def _alb_to_target_group_attribute_delay_timeout(value) # wait before changing the state of a deregistering target from draining to unused 0-3600 seconds. { "deregistration_delay.timeout_seconds": value } end
_alb_to_target_group_stickiness(value)
click to toggle source
# File lib/kumogata/template/alb.rb, line 40 def _alb_to_target_group_stickiness(value) # 1 second to 1 week (604800 seconds). The default value is 1 day (86400 seconds). { "stickiness.enabled": true, "stickiness.type": "lb_cookie", "stickiness.lb_cookie.duration_seconds": value } end
_and(conditions)
click to toggle source
# File lib/kumogata/template/helper.rb, line 201 def _and(conditions) _{ Fn__And conditions } end
_api_gateway_integration(args)
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 69 def _api_gateway_integration(args) args_proxy = _bool("proxy", args, false) args_parameters = args[:parameters] || [] integration = args[:integration] || {} return integration if integration.empty? cache_keys = integration[:cache_keys] || [] cache_keys << _api_gateway_to_parameter({ type: "method", location: "path", name: "proxy" }) if args_proxy cache_ns = integration[:cache_ns] || "" http = if args_proxy "any" else _valid_values(integration[:http], %w( delete get head options patch post put any ), "any") end responses = if integration.key? :responses integration[:responses].collect{|v| _api_gateway_integration_response(v) } else [] end responses << _api_gateway_integration_response({ template: { "application/json": "null" } }) if args_proxy pass = if args_proxy "when_no_match" else _valid_values(integration[:pass], %w( when_no_match when_no_templates never ), "") end role = _ref_attr_string("role", "Arn", integration) parameters = {} args_parameters.collect do |v| k = _api_gateway_to_parameter({ type: "integration", location: v[:location], name: v[:name] }) parameters[k] = _api_gateway_to_parameter(v) end (integration[:parameters] || []).collect do |v| k = _api_gateway_to_parameter({ type: "integration", location: v[:location], name: v[:name] }) parameters[k] = v[:value] end # RequestTemplates # - Key: The content type value # - Value: the template http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html templates = integration[:templates] || {} type = if args_proxy "http_proxy" else _valid_values(integration[:type], %w( mock http http_proxy aws aws_proxy ), "http") end uri = case type when /http/ _ref_string("uri", integration) when /aws/ _iam_arn("api-gateway", integration) else "" end uri = _join([ uri, "{proxy}" ], "/") if args_proxy _{ CacheKeyParameters cache_keys unless cache_keys.empty? CacheNamespace cache_ns unless cache_ns.empty? Credentials role unless role.empty? IntegrationHttpMethod http.upcase if type != "mock" IntegrationResponses responses unless responses.empty? PassthroughBehavior pass.upcase unless pass.empty? RequestParameters parameters unless parameters.empty? RequestTemplates templates unless templates.empty? Type type.upcase Uri uri unless uri.empty? } end
_api_gateway_integration_response(args)
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 144 def _api_gateway_integration_response(args) parameter = args[:parameter] || {} template = args[:template] || {} selection = args[:selection] || "" status = args[:status] || 200 _{ ResponseParameters parameter unless parameter.empty? ResponseTemplates template unless template.empty? SelectionPattern selection unless selection.empty? StatusCode status } end
_api_gateway_method_settings(args)
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 206 def _api_gateway_method_settings(args) (args[:settings] || []).collect do |setting| cache = setting[:cache] || {} data_trace = _bool("data_trace", setting, false) http = setting[:http] || "*" logging = _valid_values(setting[:logging], %w( off error info ), "info") metrics = _bool("metrics", setting, false) resource = setting[:resource] || "/*" throtting = setting[:throtting] || {} _{ CacheDataEncrypted cache[:encrypted] unless cache.empty? CacheTtlInSeconds cache[:ttl] unless cache.empty? CachingEnabled cache.empty? ? false : true DataTraceEnabled data_trace HttpMethod http LoggingLevel logging.upcase MetricsEnabled metrics ResourcePath resource ThrottlingBurstLimit throtting[:burst] unless throtting.empty? ThrottlingRateLimit throtting[:rate] unless throtting.empty? } end end
_api_gateway_quota(args)
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 240 def _api_gateway_quota(args) quota = args[:quota] || {} return quota if quota.empty? offset = quota[:offset] || "" period = _valid_values(quota[:period], %w( day week month ), "month") _{ Limit quota[:limit] Offset offset unless offset.empty? Period period.upcase } end
_api_gateway_responses(args)
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 158 def _api_gateway_responses(args) (args[:responses] || []).collect do |response| models = response[:models] || [] parameters = response[:parameters] || [] status = response[:status] || 200 _{ ResponseModels models unless models.empty? ResponseParameters parameters unless parameters.empty? StatusCode status } end end
_api_gateway_stage_description(args)
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 172 def _api_gateway_stage_description(args) description = args[:stage_description] || {} return description if description.empty? cache = description[:cache] || {} certificate = _ref_string_default("certificate", description, "certificate") data_trace = _bool("data_trace", description, false) description_desc = description[:description] || "" logging = _valid_values(description[:logging], %w( off error info ), "off") method = _api_gateway_method_settings(description) metrics = _bool("metrics", description, false) stage = _name("stage", description) throtting = description[:throtting] || {} variables = description[:variables] || {} _{ CacheClusterEnabled true if cache.key? :cluster CacheClusterSize cache[:size] unless cache.empty? CacheDataEncrypted true if cache.key? :encrypted CacheTtlInSeconds cache[:ttl] unless cache.empty? CachingEnabled cache.empty? ? false : true ClientCertificateId certificate unless certificate.empty? DataTraceEnabled data_trace Description description unless description_desc.empty? LoggingLevel logging.upcase MethodSettings method unless method.empty? MetricsEnabled metrics StageName stage ThrottlingBurstLimit throtting[:burst] unless throtting.empty? ThrottlingRateLimit throtting[:rate] unless throtting.empty? Variables variables unless variables.empty? } end
_api_gateway_stage_keys(args)
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 58 def _api_gateway_stage_keys(args) (args[:stage_keys] || []).collect do |key| rest = _ref_string("rest", key, "reset api") stage = _ref_string("stage", key) _{ RestApiId rest StageName stage } end end
_api_gateway_stages(args)
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 231 def _api_gateway_stages(args) (args[:stages] || []).collect do |stage| _{ ApiId _ref_string("rest", stage, "rest api") Stage _ref_string("stage", stage, "stage") } end end
_api_gateway_throttle(args)
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 254 def _api_gateway_throttle(args) throttle = args[:throttle] || {} return throttle if throttle.empty? _{ BurstLimit throttle[:bust] RateLimit throttle[:rate] } end
_api_gateway_to_parameter(args)
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 6 def _api_gateway_to_parameter(args) type = _valid_values(args[:type], %w( integration method ), "method") location = _valid_values(args[:location], %w( querystring path header ), "path") operation = args[:operation] || "request" "#{type}.#{operation}.#{location}.#{args[:name]}" end
_api_gateway_to_parameter_headers(kind)
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 13 def _api_gateway_to_parameter_headers(kind) headers = case kind when "aws" [ { name: "X-AWS-Request-Id", value: "context.requestId" }, { name: "X-AWS-API-Id", value: "context.apiId" }, ] when "cognito" [ { name: "X-AWS-Cognito-Identity-Id", value: "context.identity.cognitoIdentityId" }, { name: "X-AWS-Cognito-Identity-Pool-Id", value: "context.identity.cognitoIdentityPoolId" }, { name: "X-AWS-Cognito-Authentication-Type", value: "context.identity.cognitoAuthenticationType" }, { name: "X-AWS-Cognito-Authentication-Provider", value: "context.identity.cognitoAuthenticationProvider" }, ] else [] end return headers if headers.empty? headers.collect{|v| v.merge!({ location: "header" }) } end
_api_gateway_to_parameter_response_headers(args = {})
click to toggle source
# File lib/kumogata/template/api-gateway.rb, line 36 def _api_gateway_to_parameter_response_headers(args = {}) headers = {} key = _api_gateway_to_parameter({ operation: "response", location: "header", name: "Access-Control-Allow-Methods" }) headers[key] = "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'" key = _api_gateway_to_parameter({ operation: "response", location: "header", name: "Access-Control-Allow-Headers" }) allow_headers = %w( Content-Type Authorization X-Amz-Date X-Api-Key X-Amz-Security-Token) allow_headers += args[:allow_headers] if args.key? :allow_headers headers[key] = sprintf("'%s'", allow_headers.join(',')) key = _api_gateway_to_parameter({ operation: "response", location: "header", name: "Access-Control-Allow-Origin" }) headers[key] = "'*'" headers end
_arn(arn, value)
click to toggle source
# File lib/kumogata/template/iam.rb, line 566 def _arn(arn, value) "#{arn}#{value}".include?("${") ? _sub("#{arn}#{value}") : "#{arn}#{value}" end
_array(args)
click to toggle source
# File lib/kumogata/template/helper.rb, line 7 def _array(args) if args.is_a? String [ args ] elsif args.is_a? Hash args.values else args end end
_attr_string(name, attr, ref_name = '')
click to toggle source
# File lib/kumogata/template/helper.rb, line 197 def _attr_string(name, attr, ref_name = '') _{ Fn__GetAtt [ _resource_name(name, ref_name), attr ] } end
_autoscaling_metrics()
click to toggle source
# File lib/kumogata/template/autoscaling.rb, line 65 def _autoscaling_metrics _{ Granularity "1Minute" Metrics %w( GroupMinSize GroupMaxSize GroupDesiredCapacity GroupInServiceInstances GroupPendingInstances GroupStandbyInstances GroupTerminatingInstances GroupTotalInstances ) } end
_autoscaling_notification(args)
click to toggle source
# File lib/kumogata/template/autoscaling.rb, line 79 def _autoscaling_notification(args) types = args[:types] || [] %w( EC2_INSTANCE_LAUNCH EC2_INSTANCE_LAUNCH_ERROR EC2_INSTANCE_TERMINATE EC2_INSTANCE_TERMINATE_ERROR TEST_NOTIFICATION ).collect{|v| types << "autoscaling:#{v}" } if types.empty? topic = _ref_attr_string("topic", "Arn", args, "topic") topic = _ref_string("topic_arn", args) if topic.empty? _{ NotificationTypes types TopicARN topic } end
_autoscaling_step(args)
click to toggle source
# File lib/kumogata/template/autoscaling.rb, line 98 def _autoscaling_step(args) lower = args[:lower] || "" upper = args[:upper] || "" scaling = args[:scaling] || 1 _{ MetricIntervalLowerBound lower unless lower.to_s.empty? MetricIntervalUpperBound upper unless upper.to_s.empty? ScalingAdjustment scaling } end
_autoscaling_terminations(args)
click to toggle source
# File lib/kumogata/template/autoscaling.rb, line 117 def _autoscaling_terminations(args) (args[:terminations] || []).collect do |termination| case termination.downcase when "old instance" "OldestInstance" when "new instance" "NewestInstance" when "old launch" "OldestLaunchConfiguration" when "close" "ClosestToNextInstanceHour" else "Default" end end end
_autoscaling_to_adjustment(value)
click to toggle source
# File lib/kumogata/template/autoscaling.rb, line 6 def _autoscaling_to_adjustment(value) return value if value.nil? case value.downcase when "change" "ChangeInCapacity" when "exact" "ExactCapacity" when "percent" "PercentChangeInCapacity" else value end end
_autoscaling_to_metric(value)
click to toggle source
# File lib/kumogata/template/autoscaling.rb, line 20 def _autoscaling_to_metric(value) return value if value.nil? case value.downcase when "min" "Minimum" when "max" "Maximum" when "avg" "Average" else value end end
_autoscaling_to_policy(value)
click to toggle source
# File lib/kumogata/template/autoscaling.rb, line 34 def _autoscaling_to_policy(value) return value if value.nil? case value.downcase when "simple" "SimpleScaling" when "step" "StepScaling" else value end end
_autoscaling_to_schedued_recurrence(value)
click to toggle source
# File lib/kumogata/template/autoscaling.rb, line 46 def _autoscaling_to_schedued_recurrence(value) case value when "every 5 min" "*/5 * * * *" when "every 30 min" "0,30 * * * *" when "every 1 hour" "0 * * * *" when "every day" "0 0 * * *" when "every week" "0 0 * * Tue" when /\*/ value else _timestamp_utc(value, "cron") end end
_availability_zone(args, use_subnet = true, prefix = "zone name")
click to toggle source
# File lib/kumogata/template/helper.rb, line 370 def _availability_zone(args, use_subnet = true, prefix = "zone name") zone = args.clone zone.delete(:ref_subnet) if use_subnet == false if zone.key? :ref_subnet _ref_attr_string("subnet", "AvailabilityZone", zone, "subnet") else _ref_string("az", zone, prefix) end end
_availability_zones(args, use_subnet = true)
click to toggle source
# File lib/kumogata/template/helper.rb, line 380 def _availability_zones(args, use_subnet = true) zone = args.dup if use_subnet == false zone.delete(:ref_subnet) zone.delete(:ref_subnets) end if zone.key? :ref_subnet [ _attr_string(args[:ref_subnet], "AvailabilityZone", "subnet") ] elsif zone.key? :ref_subnets zone[:ref_subnets].collect{|v| _ref_attr_string("subnet", "AvailabilityZone", { ref_subnet: v }, "subnet") } elsif args.key? :ref_azs zone[:ref_azs].collect{|v| _ref_string("azs", { ref_azs: v }, "zone") } elsif args.key? :ref_az [ _ref_string("az", zone, "zone") ] else _azs(_region) end end
_azs(region)
click to toggle source
# File lib/kumogata/template/helper.rb, line 193 def _azs(region) _{ Fn__GetAZs region } end
_base64(data)
click to toggle source
# File lib/kumogata/template/helper.rb, line 225 def _base64(data) data = data.undent if data.is_a? String _{ Fn__Base64 data } end
_base64_shell(data, shell = "/bin/bash")
click to toggle source
# File lib/kumogata/template/helper.rb, line 230 def _base64_shell(data, shell = "/bin/bash") if data.is_a? Array _base64(_join(data.insert(0, "#!#{shell}"), "\n")) else _base64(_join([ "#!#{shell}", data ], "\n")) end end
_bool(name, args, default = false)
click to toggle source
# File lib/kumogata/template/helper.rb, line 17 def _bool(name, args, default = false) bool = args.key?(name.to_sym) ? args[name.to_sym] : default bool.to_s == 'true' end
_capitalize(name)
click to toggle source
# File lib/kumogata/template/helper.rb, line 26 def _capitalize(name) name.split(' ').map(&:capitalize).join() end
_certificate_validations(args)
click to toggle source
# File lib/kumogata/template/certificate.rb, line 6 def _certificate_validations(args) validations = args[:validation] || [] return [ _{ DomainName _ref_string("domain", args, "domain") ValidationDomain _ref_string("domain", args, "domain") } ] if validations.empty? validations.collect do |validation| domain = _ref_string("domain", validation, "domain") validation = _ref_string("validation", validation, "domain") _{ DomainName domain ValidationDomain validation || domain } end end
_cloudfront_cache_behavior(args, origins = [], default = false)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 65 def _cloudfront_cache_behavior(args, origins = [], default = false) allowed_methods = if args.key? :allowed_methods case args[:allowed_methods] when "with options" %w( GET HEAD OPTIONS ) when "all" %w( DELETE GET HEAD OPTIONS PATCH POST PUT ) else %w( HEAD GET ) end else "" end cached_methods = if args.key? :cached_methods case args[:cached_methods] when "with options" %w( GET HEAD OPTIONS ) else %w( HEAD GET ) end else "" end compress = if args.key? :compress _bool("compress", args, false) else "" end default_ttl = args[:default_ttl] || 86400 forwarded_values = _cloudfront_forwarded_values(args[:forwarded] || {}) lambda = (args[:lambda_functions] || []).collect{|v| _cloudfront_lambda(v) } max_ttl = args[:max_ttl] || 31536000 min_ttl = args[:min_ttl] || 0 path = args[:path] smooth = if args.key? :smooth _bool("smooth", args, false) else "" end target = args[:target] || "" target = origins[0][:id] if target.empty? and (origins[0] and origins[0].is_a? Hash and origins[0][:id]) trusted = args[:trusted] || "" viewer = _valid_values(args[:viewer], %w( allow-all redirect-to-https https-only ), "redirect-to-https") _{ AllowedMethods allowed_methods unless allowed_methods.empty? CachedMethods cached_methods unless cached_methods.empty? Compress compress unless compress.empty? DefaultTTL default_ttl unless default_ttl.nil? ForwardedValues forwarded_values LambdaFunctionAssociations lambda unless lambda.empty? MaxTTL max_ttl unless max_ttl.nil? MinTTL min_ttl unless min_ttl.nil? PathPattern path if default == false SmoothStreaming smooth unless smooth.empty? TargetOriginId target TrustedSigners trusted unless trusted.empty? ViewerProtocolPolicy viewer } end
_cloudfront_custom_error(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 173 def _cloudfront_custom_error(args) error_min_ttl = args[:error_min_ttl] || 300 error_code = args[:error_code] || 404 response_code = if args.key? :response_code args[:response_code] || 404 else error_code end response_page = unless response_code.nil? args[:response_page] || "/#{response_code}.html" else "" end _{ ErrorCachingMinTTL error_min_ttl ErrorCode error_code ResponseCode response_code ResponsePagePath response_page } end
_cloudfront_custom_errors(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 197 def _cloudfront_custom_errors(args) (args || []).collect{|error| _cloudfront_custom_error(error) } end
_cloudfront_custom_origin(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 250 def _cloudfront_custom_origin(args) http_port = args[:http] || 80 https_port = args[:https] || 443 keepalive = args[:keepalive] || 5 protocol = _valid_values(args[:protocol], %w( https-only http-only match-viewer ), "match-viewer") read_timeout = args[:read_timeout] || 30 ssl_protocols = (_array(args[:ssl_protocols]) || [ '' ] ).collect{|v| _valid_values(v, %w( SSLv3 TLSv1 TLSv1.1 TLSv1.2 ), "TLSv1.1") } _{ HTTPPort http_port HTTPSPort https_port OriginKeepaliveTimeout keepalive OriginProtocolPolicy protocol OriginReadTimeout read_timeout OriginSSLProtocols ssl_protocols } end
_cloudfront_distribution_config(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 6 def _cloudfront_distribution_config(args) aliases = args[:aliases] || [] behaivors = if args.key? :behaivors args[:behaivors].collect{|v| _cloudfront_cache_behavior(v) } else "" end comment = args[:comment] || "" custom_errors = if args.key? :custom_errors _cloudfront_custom_errors(args[:custom_errors]) else [] end default_cache = if args.key? :default_cache _cloudfront_cache_behavior(args[:default_cache], args[:origins], true) else "" end default_root = args[:default_root] || "index.html" enabled = _bool("enabled", args, true) http = _valid_values(args[:http], %w( http1.1 http2 ), "http2") logging = if args.key? :logging _cloudfront_logging(args[:logging]) else "" end origins = _cloudfront_origins(args[:origins]) price = args[:price] || "" restrictions = args[:restrictions] || "" viewer_cert = if args.key? :viewer_cert _cloudfront_viewer_cert(args[:viewer_cert]) else "" end web_acl = args[:web_acl] || "" _{ Aliases aliases unless aliases.empty? CacheBehaviors behaivors unless behaivors.empty? Comment comment unless comment.empty? CustomErrorResponses custom_errors unless custom_errors.empty? DefaultCacheBehavior default_cache unless default_cache.empty? DefaultRootObject default_root unless default_root.empty? Enabled enabled HttpVersion http unless http.empty? Logging logging unless logging.empty? Origins origins PriceClass price unless price.empty? Restrictions restrictions unless restrictions.empty? ViewerCertificate viewer_cert unless viewer_cert.empty? WebACLId web_acl unless web_acl.empty? } end
_cloudfront_forwarded_values(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 140 def _cloudfront_forwarded_values(args) cookies = if args.key? :cookies _cloudfront_forwared_cookies(args[:cookies]) else "" end headers = args[:headers] || [] query_string = _bool("query_string", args, false) query_string_keys = args[:query_string_keys] || [] _{ Cookies cookies unless cookies.empty? Headers headers unless headers.empty? QueryString query_string QueryStringCacheKeys query_string_keys unless query_string_keys.empty? } end
_cloudfront_lambda(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 159 def _cloudfront_lambda(args) return '' if args.empty? event = _valid_values(args[:envet], %w( viewer-request origin-request origin-response viewer-response ), 'viewer-request') function = _ref_string('version', args, 'lambda version') _{ EventType event LambdaFunctionARN function } end
_cloudfront_logging(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 201 def _cloudfront_logging(args) bucket = _ref_attr_string("bucket", "DomainName", args, "bucket") include_cookies = if args.key? :include_cookies _bool("include_cookies", args, false) else "" end prefix = args[:prefix] || "" _{ Bucket bucket IncludeCookies include_cookies unless include_cookies.empty? Prefix prefix unless prefix.empty? } end
_cloudfront_origin(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 218 def _cloudfront_origin(args) custom = if args.key? :custom _cloudfront_custom_origin(args[:custom]) else {} end domain = _ref_attr_string("domain", "DomainName", args, "bucket") id = args[:id] headers = if args.key? :headers _cloudfront_origin_headers(args[:headers]) else "" end path = args[:path] || "" s3 = _cloudfront_s3_origin(args) _{ CustomOriginConfig custom if s3.empty? and !custom.empty? DomainName "#{domain}.s3.#{DOMAIN}" Id id OriginCustomHeaders headers unless headers.empty? OriginPath path unless path.empty? S3OriginConfig s3 if custom.empty? } end
_cloudfront_origin_headers(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 282 def _cloudfront_origin_headers(args) name = args[:name] value = args[:value] _{ HeaderName name HeaderValue value } end
_cloudfront_origins(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 246 def _cloudfront_origins(args) (args || []).collect{|origin| _cloudfront_origin(origin) } end
_cloudfront_s3_origin(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 271 def _cloudfront_s3_origin(args) s3 = _ref_string("s3", args, 'origin access identity') return {} if s3.empty? origin = _join([ 'origin-access-identity', 'cloudfront', s3 ], '/') _{ OriginAccessIdentity origin unless origin.empty? } end
_cloudfront_viewer_cert(args)
click to toggle source
# File lib/kumogata/template/cloudfront.rb, line 292 def _cloudfront_viewer_cert(args) acm = _ref_string("acm", args) default = if args.key? :default _bool("default", args, false) else "" end iam = args[:iam] || "" min_protocol = _valid_values(args[:min_protocol], %w( SSLv3 | TLSv1 | TLSv1_2016 | TLSv1.1_2016 | TLSv1.2_2018 ), "TLSv1.1_2016") ssl = _valid_values(args[:ssl], %w( vip sni-only ), "sni-only") _{ AcmCertificateArn acm unless acm.empty? CloudFrontDefaultCertificate default unless default.empty? IamCertificateId iam unless iam.empty? MinimumProtocolVersion min_protocol unless min_protocol.empty? SslSupportMethod ssl unless acm.empty? and iam.empty? } end
_cloudwatch_actions(args)
click to toggle source
# File lib/kumogata/template/cloudwatch.rb, line 251 def _cloudwatch_actions(args) (args[:actions] || args[:ref_actions] || []).collect do |action| if action =~ /ec2 (\w)/ _cloudwatch_to_ec2_action($1) else if args.key? :ref_actions _ref_string("action", { ref_action: action }) else action end end end end
_cloudwatch_dimension(args)
click to toggle source
# File lib/kumogata/template/cloudwatch.rb, line 244 def _cloudwatch_dimension(args) _{ Name args[:name] Value _ref_string("value", args) } end
_cloudwatch_to_ec2_action(value)
click to toggle source
# File lib/kumogata/template/cloudwatch.rb, line 239 def _cloudwatch_to_ec2_action(value) value = _valid_values(value, %w( recover stop terminate reboot ), "recover") _join([ "arn:aws:automate:", _region, ":ec2:#{value}" ], "") end
_cloudwatch_to_metric(value)
click to toggle source
# File lib/kumogata/template/cloudwatch.rb, line 44 def _cloudwatch_to_metric(value) prefix = $1 if value =~ /^(\w+) / # http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CW_Support_For_AWS.html case prefix when "ec2", "ec2 spot", "ecs", "eb", "ebs", "efs", "elb", "alb", "emr", "es", "transcoder", "iot", "kinesis firehose", "firehose", "kinesis", "kms", "lambda", "ml", "ops works", "ow", "polly", "redshift", "rds", "route53", "ses", "sns", "sqs", "s3", "swf", "storage", "storage gateway", "waf", "work spaces", "ws" value.slice!(/^#{prefix} /) value = value.split(" ").collect! do |v| case v when "cpu", "iops" v.upcase else v.capitalize end end.join("") end value end
_cloudwatch_to_namespace(value)
click to toggle source
# File lib/kumogata/template/cloudwatch.rb, line 71 def _cloudwatch_to_namespace(value) return value if value.include? "/" # http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-namespaces.html value = case value when "api gateway" "ApiGateway" when "auto scaling" "AutoScaling" when "billing" "Billing" when "cloud front" "CloudFront" when "cloud search" "CloudSearch" when "cloudwatch events" "Events" when "cloudwatch logs" "Logs" when "dynamodb", "dynamod db" "DynamoDB" when "ec2" "EC2" when "ec2 spot" "EC2Spot" when "ecs" "ECS" when "eb" "ElasticBeanstalk" when "ebs" "EBS" when "efs" "EFS" when "elb" "ELB" when "alb" "ApplicationELB" when "transcoder" "ElasticTranscoder" when "elasti cache", "cache" "ElastiCache" when "es" "ES" when "emr" "ElasticMapReduce" when "iot" "IoT" when "kms" "KMS" when "kinesis analytics" "KinesisAnalytics" when "kinesis firehose", "firehose" "Firehose" when "kinesis" "Kinesis" when "lambda" "Lambda" when "ml" "ML" when "ops works", "ow" "OpsWorks" when "polly" "Polly" when "redshift" "Redshift" when "rds" "RDS" when "route53" "Route53" when "ses" "SES" when "sns" "SNS" when "sqs" "SQS" when "s3" "S3" when "swf" "SWF" when "storage", "storage gateway" "StorageGateway" when "waf" "WAF" when "work spaces", "ws" "WorkSpaces" end "AWS/#{value}" end
_cloudwatch_to_operator(value)
click to toggle source
# File lib/kumogata/template/cloudwatch.rb, line 160 def _cloudwatch_to_operator(value) case value when ">=" "GreaterThanOrEqualToThreshold" when ">" "GreaterThanThreshold" when "<=" "LessThanOrEqualToThreshold" when "<" "LessThanThreshold" else _valid_values(value, %w( GreaterThanOrEqualToThreshold GreaterThanThreshold LessThanOrEqualToThreshold LessThanThreshold ), "GreaterThanThreshold") end end
_cloudwatch_to_period(value)
click to toggle source
# File lib/kumogata/template/cloudwatch.rb, line 6 def _cloudwatch_to_period(value) return value if value.nil? case value when "1m" 60 when "5m" 300 when "15m" 900 when "1h" 3600 when "6h" 21600 when "1d" 86400 else value.to_i end end
_cloudwatch_to_statistic(value)
click to toggle source
# File lib/kumogata/template/cloudwatch.rb, line 26 def _cloudwatch_to_statistic(value) return value if value.nil? case value.downcase when "sample" "SampleCount" when "avg" "Average" when "Sum" "Sum" when "min" "Minimum" when "max" "Maximum" else value end end
_cloudwatch_to_unit(value)
click to toggle source
# File lib/kumogata/template/cloudwatch.rb, line 178 def _cloudwatch_to_unit(value) case value when "sec" "Seconds" when "ms" "Microseconds" when "mms" "Milliseconds" when "B" "Bytes" when "KB" "Kilobytes" when "MB" "Megabytes" when "GB" "Gigabytes" when "TB" "Terabytes" when "b" "Bits" when "kb", "Kb" "Kilobits" when "mb", "Mb" "Megabits" when "gb", "Gb" "Gigabits" when "tb", "Tb" "Terabits" when "%", "percent" "Percent" when "count" "Count" when "B/s" "Bytes/Second" when "KB/s" "Kilobytes/Second" when "MB/s" "Megabytes/Second" when "GB/s" "Gigabyes/Second" when "TB/s" "Terabytes/Second" when "bps" "Bits/Second" when "kbps" "Kilobits/Second" when "mbps" "Megabits/Second" when "gbps" "Gigabits/Second" when "tbps" "Terabits/Second" when "cps" "Count/Second" else _valid_values(value, %w(Seconds Microseconds Milliseconds Bytes Kilobytes Megabytes Gigabytes Terabytes Bits Kilobits Megabits Gigabits Terabits Percent Count Bytes/Second Kilobytes/Second Megabytes/Second Gigabytes/Second Terabytes/Second Bits/Second Kilobits/Second Megabits/Second Gigabits/Second Terabits/Second Count/Second None), "") end end
_codebuild_artifacts(args)
click to toggle source
# File lib/kumogata/template/codebuild.rb, line 33 def _codebuild_artifacts(args) name = args[:name] || "" ns = args[:ns] || "" packaging = args[:packaging] || "" path = args[:path] || "" type = _valid_values(args[:type], %w( codepipeline no_artifacts s3 ), "no_artifacts") _{ Location location if type != "codepipeline" and type != "no_artifacts" Name name if type != "codepipeline" and type != "no_artifacts" NamespaceType ns if type != "codepipeline" and type != "no_artifacts" Packaging packaging if type != "codepipeline" and type != "no_artifacts" Path path unless path.empty? Type type } end
_codebuild_environement(args)
click to toggle source
# File lib/kumogata/template/codebuild.rb, line 50 def _codebuild_environement(args) compute = _codebuild_to_compute(args[:compute]) env_hash = _codebuild_environement_hash(args[:env]) image = args[:image] _{ ComputeType compute EnvironmentVariables env_hash Image image Type "LINUX_CONTAINER" } end
_codebuild_environement_hash(args)
click to toggle source
# File lib/kumogata/template/codebuild.rb, line 63 def _codebuild_environement_hash(args) (args || {}).collect do |name, value| _{ Name name Value value } end end
_codebuild_source(args)
click to toggle source
# File lib/kumogata/template/codebuild.rb, line 72 def _codebuild_source(args) build = args[:build] || "" location = args[:location] || "" type = _codebuild_source_type(args[:type]) _{ BuildSpec build unless build.empty? Location location unless type == "CODEPIPELINE" Type type } end
_codebuild_source_type(value)
click to toggle source
# File lib/kumogata/template/codebuild.rb, line 19 def _codebuild_source_type(value) case value when "codecommit", "commit" "CODECOMMIT" when "codepipeline", "pipeline" "CODEPIPELINE" when "github", "gh" "GITHUB" when "s3" "S3" end end
_codebuild_to_compute(value)
click to toggle source
# File lib/kumogata/template/codebuild.rb, line 6 def _codebuild_to_compute(value) case value when "small" "BUILD_GENERAL1_SMALL" when "medium" "BUILD_GENERAL1_MEDIUM" when "large" "BUILD_GENERAL1_LARGE" else "BUILD_GENERAL1_MEDIUM" end end
_codecommit_triggers(args)
click to toggle source
# File lib/kumogata/template/codecommit.rb, line 6 def _codecommit_triggers(args) (args[:trigger] || []).each do |trigger| _{ Branches trigger[:branchs] || [] CustomData trigger[:custom] || "" DestinationArn trigger[:dest] || "" Events trigger[:events] || [] Name trigger[:name] || "" } end end
_codedeploy_alarm(args)
click to toggle source
# File lib/kumogata/template/codedeploy.rb, line 16 def _codedeploy_alarm(args) alarm = args[:alarm] || "" return alarm if alarm.empty? alarms = alarm[:alarms].collect{|v| _{ Name v } } enabled = _bool("enabled", args, true) ignore = _bool("ignore", args, false) _{ Alarms alarms Enabled enabled IgnorePollAlarmFailure ignore } end
_codedeploy_deployment(args)
click to toggle source
# File lib/kumogata/template/codedeploy.rb, line 31 def _codedeploy_deployment(args) description = args[:description] || "" ignore = _bool("ignore", args, true) revision = _codedeploy_revision(args[:revision]) _{ Description description unless description.empty? IgnoreApplicationStopFailures ignore Revision revision } end
_codedeploy_github(args)
click to toggle source
# File lib/kumogata/template/codedeploy.rb, line 64 def _codedeploy_github(args) commit = args[:commit] || "" repository = args[:repository] || "" _{ CommitId commit Repository repository } end
_codedeploy_minimum(args)
click to toggle source
# File lib/kumogata/template/codedeploy.rb, line 6 def _codedeploy_minimum(args) type = _valid_values(args[:type], %w( host_count fleet_percent ), "fleet_percent") value = args[:value] _{ Type type.upcase Value value } end
_codedeploy_revision(args)
click to toggle source
# File lib/kumogata/template/codedeploy.rb, line 43 def _codedeploy_revision(args) github = if args.key? :github _codedeploy_github(args[:github]) else "" end s3 = if args.key? :s3 _codedeploy_s3(args[:s3]) else "" end _{ GitHubLocation github unless github.empty? RevisionType github.empty? ? "S3" : "GitHub" S3Location s3 unless s3.empty? } end
_codedeploy_s3(args)
click to toggle source
# File lib/kumogata/template/codedeploy.rb, line 74 def _codedeploy_s3(args) bucket = _ref_string("bucket", args, "bucket") key = _ref_string("key", args) bundle = _valid_values(args[:bundle], %w( tar zip ), "zip") etag = _ref_string("etag", args) version = _ref_string("version", args) _{ Bucket bucket Key key BundleType bundle.capitalize ETag etag unless etag.empty? Version version } end
_codedeploy_tag_filters(args)
click to toggle source
# File lib/kumogata/template/codedeploy.rb, line 90 def _codedeploy_tag_filters(args) key = args[:key] || "" type = _valid_values(args[:type], %w( key_only value_only key_and_value ), "key_and_value") value = args[:value] || "" _{ Key key Type type.upcase Value value } end
_cognito_admin_config(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 58 def _cognito_admin_config(args) admin_config = args[:admin_config] || {} return admin_config if admin_config.empty? invite = _cognito_invite(admin_config) unused = admin_config[:unused] || 7 _{ AllowAdminCreateUserOnly _bool("allow", admin_config, false) InviteMessageTemplate invite unless invite.empty? UnusedAccountValidityDays unused } end
_cognito_device_config(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 90 def _cognito_device_config(args) device_config = args[:device_config] || {} return device_config if device_config.empty? _{ ChallengeRequiredOnNewDevice _bool("challenge", device_config, false) DeviceOnlyRememberedOnUserPrompt _bool("device_only", device_config, false) } end
_cognito_email_config(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 100 def _cognito_email_config(args) email_config = args[:email_config] || {} return email_config if email_config.empty? reply_to = _ref_string_default("reply_to", email_config) source = _ref_string_default("source", email_config) _{ ReplyToEmailAddress reply_to unless reply_to.empty? SourceArn source } end
_cognito_email_verify(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 113 def _cognito_email_verify(args) email_verify = args[:email_verify] || {} return {} if email_verify.empty? { message: email_verify[:message] || "Your verification code is {####}.", subject: email_verify[:subject] || "Your verification code", } end
_cognito_invite(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 72 def _cognito_invite(args) invite = args[:invite] || {} return invite if invite.empty? email_message = _ref_string_default("email_message", invite, "Your username is {username} and temporary password is {####}.") email_subject = _ref_string_default("email_subject", invite, "Your temporary password") sms = _ref_string_default("sms", invite, "Your username is {username} and temporary password is {####}.") _{ EmailMessage email_message EmailSubject email_subject SMSMessage sms } end
_cognito_lambda_config(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 123 def _cognito_lambda_config(args) lambda_config = args[:lambda_config] || {} return {} if lambda_config.empty? create_auth = _ref_string_default("create_auth", lambda_config) custom_message = _ref_string_default("custom_message", lambda_config) defined_auth = _ref_string_default("defined_auth", lambda_config) post_auth = _ref_string_default("post_auth", lambda_config) post_confirm = _ref_string_default("post_confirm", lambda_config) pre_auth = _ref_string_default("pre_auth", lambda_config) pre_sign = _ref_string_default("pre_sign", lambda_config) verify_auth = _ref_string_default("verify_auth", lambda_config) _{ CreateAuthChallenge create_auth unless create_auth.empty? CustomMessage custom_message unless custom_message.empty? DefineAuthChallenge defined_auth unless defined_auth.empty? PostAuthentication post_auth unless post_auth.empty? PostConfirmation post_confirm unless post_confirm.empty? PreAuthentication pre_auth unless pre_auth.empty? PreSignUp pre_sign unless pre_sign.empty? VerifyAuthChallengeResponse verify_auth unless verify_auth.empty? } end
_cognito_password_policy(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 157 def _cognito_password_policy(args) policy = args[:password] || {} _{ MinimumLength policy[:min] || 6 RequireLowercase _bool("lowercase", policy, false) RequireNumbers _bool("numbers", policy, false) RequireSymbols _bool("symbols", policy, false) RequireUppercase _bool("uppercase", policy, false) } end
_cognito_policies(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 148 def _cognito_policies(args) policies = args[:policies] || {} password = _cognito_password_policy(policies) _{ PasswordPolicy password } end
_cognito_providers(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 6 def _cognito_providers(args) providers = args[:providers] || {} return providers if providers.empty? # providers: [ ref_client: 'admin', ref_name: 'admin' ] providers.collect do |provider| _{ ClientId _ref_string("client", provider, "user pool client") ProviderName _ref_attr_string("pool", "ProviderName", provider, "user pool") ServerSideTokenCheck _bool("check", provider, false) } end end
_cognito_push_sync(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 31 def _cognito_push_sync(args) push_sync = args[:push_sync] || {} return push_sync if push_sync.empty? _{ ApplicationArns push_sync[:applications] RoleArn push_sync[:role] } end
_cognito_roles(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 45 def _cognito_roles(args) roles = args[:roles] || {} return roles if roles.empty? unauth = _ref_attr_string("unauth", "Arn", roles, "role") auth = _ref_attr_string("auth", "Arn", roles, "role") _{ unauthenticated unauth unless unauth.empty? authenticated auth } end
_cognito_roles_mappings(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 41 def _cognito_roles_mappings(args) # T.B.D end
_cognito_schemas(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 169 def _cognito_schemas(args) (args[:schemas] || []).collect do |schema| data_type = schema[:data_type] || "String" # String, Number, DateTime, or Boolean number = schema[:number] || {} string = schema[:string] || {} _{ AttributeDataType data_type unless data_type.empty? DeveloperOnlyAttribute _bool("developer", schema, false) Mutable _bool("mutable", schema, true) Name schema[:name] NumberAttributeConstraints do MaxValue number[:max] MinValue number[:min] end unless number.empty? StringAttributeConstraints do MaxLength string[:max] MinLength string[:min] end unless string.empty? Required _bool("required", schema, true) } end end
_cognito_sms_config(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 193 def _cognito_sms_config(args) sms_config = args[:sms_config] || {} return sms_config if sms_config.empty? external = _ref_string_default("external", sms_config) _{ ExternalId external unless external.empty? SnsCallerArn _ref_string("sns_caller", args) } end
_cognito_streams(args)
click to toggle source
# File lib/kumogata/template/cognito.rb, line 20 def _cognito_streams(args) stream = args[:stream] || {} return stream if stream.empty? _{ RoleArn stream[:role] StreamingStatus _bool("status", stream, false) ? "ENABLED" : "DISABLED" StreamName stream[:name] } end
_condition(condition)
click to toggle source
# File lib/kumogata/template/helper.rb, line 221 def _condition(condition) _{ Condition condition } end
_convert(args)
click to toggle source
# File lib/kumogata/template/iam.rb, line 209 def _convert(args) return "" if args.empty? return args if args.is_a? String result = args.collect do |k, v| case k.to_s when "ref" _{ Ref _resource_name(v) } when /ref_(.*)/ _ref_pseudo($1) else v end end (args.size == 1) ? result.first : result end
_datapipeline_parameter_objects(args)
click to toggle source
# File lib/kumogata/template/datapipeline.rb, line 6 def _datapipeline_parameter_objects(args) (args[:parameter_objects] || []).collect do |object| object.collect do |id, value| attributes = _datapipeline_parameter_objects_attributes(value) _{ Attributes attributes Id id } end end.flatten end
_datapipeline_parameter_objects_attributes(args)
click to toggle source
# File lib/kumogata/template/datapipeline.rb, line 19 def _datapipeline_parameter_objects_attributes(args) (args[:attributes] || {}).collect do |key, value| _{ Key key StringValue value } end end
_datapipeline_parameter_values(args)
click to toggle source
# File lib/kumogata/template/datapipeline.rb, line 28 def _datapipeline_parameter_values(args) (args[:parameter_values] || {}).collect do |id, value| _{ Id id StringValue value } end end
_datapipeline_pipeline_object_fields(args)
click to toggle source
# File lib/kumogata/template/datapipeline.rb, line 50 def _datapipeline_pipeline_object_fields(args) (args[:fields] || {}).collect do |key, value| _{ Key key RefValue value[:ref] if value.key? :ref StringValue value[:string] if value.key? :string } end end
_datapipeline_pipeline_objects(args)
click to toggle source
# File lib/kumogata/template/datapipeline.rb, line 37 def _datapipeline_pipeline_objects(args) (args[:objects] || []).collect do |object| object.collect do |id, value| fields = _datapipeline_pipeline_object_fields(value) _{ Fields fields Id id Name value[:name] } end end.flatten end
_depends(keys, args)
click to toggle source
# File lib/kumogata/template/helper.rb, line 289 def _depends(keys, args) return '' if keys.empty? depends = if args.key? :depends args[:depends].collect{|v| _resource_name(v) } else [] end keys.each do |v| if v.is_a? String depends << _resource_name(args[v.to_sym]) if args.key? v.to_sym else v.each_pair do |kk, vv| depends << _resource_name(args[kk.to_sym], vv) if args.key? kk.to_sym end end end depends end
_description(name)
click to toggle source
# File lib/kumogata/template/helper.rb, line 30 def _description(name) name.gsub("\n", ' '). gsub(/\s+/, ' ').gsub(/^\s/, '').gsub(/\s$/, ''). chomp.slice(0, 1024) end
_dynamodb_attribute(args)
click to toggle source
# File lib/kumogata/template/dynamodb.rb, line 6 def _dynamodb_attribute(args) attributes = [] _array(args).each do |arg| if arg.is_a? String attributes << { type: "string", value: arg } elsif arg.is_a? Hash arg.each_pair.collect{|type, value| attributes << { type: type, value: value } } end end attributes.collect do |attribute| type = case attribute[:type].to_sym when :binary "B" when :integer "N" else "S" end _{ AttributeName attribute[:value] AttributeType type } end end
_dynamodb_global(args)
click to toggle source
# File lib/kumogata/template/dynamodb.rb, line 83 def _dynamodb_global(args) index = args[:index] key_schema = _dynamodb_key_schema(args[:key_schema]) projection = _dynamodb_projection(args[:projection]) provisioned = _dynamodb_provisioned(args[:provisioned]) _{ IndexName index KeySchema key_schema Projection projection ProvisionedThroughput provisioned } end
_dynamodb_key_schema(args)
click to toggle source
# File lib/kumogata/template/dynamodb.rb, line 33 def _dynamodb_key_schema(args) schemas = [] _array(args).each do |arg| if arg.is_a? String schemas << { type: "hash", value: arg } elsif arg.is_a? Hash arg.each_pair.collect{|type, value| schemas << { type: type, value: value } } end end schemas.collect do |schema| type = case schema[:type].to_sym when :range "range" else "hash" end _{ AttributeName schema[:value] KeyType type.upcase } end end
_dynamodb_local(args)
click to toggle source
# File lib/kumogata/template/dynamodb.rb, line 97 def _dynamodb_local(args) index = args[:index] key_schema = _dynamodb_key_schema(args[:key_schema]) projection = _dynamodb_projection(args[:projection]) _{ IndexName index KeySchema key_schema Projection projection } end
_dynamodb_projection(args)
click to toggle source
# File lib/kumogata/template/dynamodb.rb, line 58 def _dynamodb_projection(args) non_key = args[:non_key] || [] type = _valid_values(args[:type], %w( keys_only include all ), "include") _{ NonKeyAttributes non_key unless non_key.empty? ProjectionType type.upcase unless type.empty? } end
_dynamodb_provisioned(args)
click to toggle source
# File lib/kumogata/template/dynamodb.rb, line 68 def _dynamodb_provisioned(args) _{ ReadCapacityUnits args[:read] || 5 WriteCapacityUnits args[:write] || args[:read] || 5 } end
_dynamodb_stream(args)
click to toggle source
# File lib/kumogata/template/dynamodb.rb, line 75 def _dynamodb_stream(args) stream = args[:stream] || "" _{ StreamViewType stream } end
_dynamodb_ttl(args)
click to toggle source
# File lib/kumogata/template/dynamodb.rb, line 109 def _dynamodb_ttl(args) ttl = args[:ttl] || {} return ttl if ttl.empty? attr = args[:attr] || "" enabled = _bool("enabled", args, true) _{ AttributeName attr unless attr.empty? Enabled enabled } end
_ec2_block_device(args)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 118 def _ec2_block_device(args) device = args[:device] || "/dev/sdb" delete = _bool("delete", args, true) encrypted = _bool("encrypted", args, false) iops = args[:iops] || 300 snapshot = args[:snapshot] || "" size = _ref_string("size", args, "volume size") type = _valid_values(args[:type], %w( io1 gp2 sc1 st1 ), "gp2") no_device = args[:no_device] || "" virtual = args[:virtual] || "" _{ DeviceName device Ebs do DeleteOnTermination delete Encrypted encrypted if encrypted == true Iops iops if type == "io1" SnapshotId snapshot if device.empty? VolumeSize size if snapshot.empty? and !size.empty? VolumeType type end NoDevice no_device unless no_device.empty? VirtualName virtual unless virtual.empty? } end
_ec2_image(args)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 175 def _ec2_image(args) return args[:image_id] if args.key? :image_id image = if args.key? :ecs "ecs official" else args[:image] || EC2_DEFAULT_IMAGE end instance_type = _ref_string("instance_type", args, "instance type") _find_in_map("AWSRegionArch2AMI#{_resource_name(image)}", _region, _find_in_map("AWSInstanceType2Arch", instance_type, "Arch")) end
_ec2_network_interface_embedded(args, is_spot = false)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 144 def _ec2_network_interface_embedded(args, is_spot = false) associate_public = _bool("associate_public", args, true) delete = _bool("delete", args, true) description = args[:description] || "" device = args[:device] || 0 group_set = _ref_array("group_set", args, "security group") groups = _ref_array("groups", args, "security group") network_interface = _ref_string("network", args) private_ip = args[:private_ip] || "" private_ips = args[:private_ips] || "" secondary_private_ip = args[:secondary_private_ip] || "" subnet = _ref_string("subnet", args, "subnet") _{ AssociatePublicIpAddress associate_public DeleteOnTermination delete Description description unless description.empty? DeviceIndex device if is_spot Groups groups unless groups.empty? else GroupSet group_set unless group_set.empty? end NetworkInterfaceId network_interface unless network_interface.empty? PrivateIpAddress private_ip if is_spot and !private_ip.empty? PrivateIpAddresses private_ips unless private_ips.empty? SecondaryPrivateIpAddressCount secondary_private_ip unless secondary_private_ip.empty? SubnetId subnet } end
_ec2_port_range(args)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 190 def _ec2_port_range(args) _{ From args[:from] || 0 To args[:to] || args[:from] || 65535 } end
_ec2_protocol_number(protocol)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 197 def _ec2_protocol_number(protocol) # http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml case protocol when 'tcp' 6 when 'udp' 17 when 'icmp' 1 else -1 end end
_ec2_security_group_egress_rule(args)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 53 def _ec2_security_group_egress_rule(args) cidr = args[:cidr] || "0.0.0.0/0" cidr_ipv6 = args[:cidr_ipv6] || "" dest_security = _ref_string("dest_security", args, "security group") description = _ref_string_default("description", args, '', "egress rule description") from = _ref_string("from", args) ip = args[:ip] || "tcp" dest_prefix = _ref_string("dest_prefix", args, "vpc endpoint") to = _ref_string("to", args) from = to if from.empty? _{ CidrIp cidr if dest_security.empty? CidrIpv6 cidr_ipv6 unless cidr_ipv6.empty? DestinationPrefixListId dest_prefix unless dest_prefix.empty? Description description FromPort from unless ip == "icmp" IpProtocol ip DestinationSecurityGroupId dest_security unless dest_security.empty? ToPort to unless ip == "icmp" } end
_ec2_security_group_egress_rules(name, args)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 43 def _ec2_security_group_egress_rules(name, args) return [] unless args.key? name.to_sym rules = [] _array(args[name.to_sym]).each do |arg| rules << _ec2_security_group_egress_rule(arg) end rules end
_ec2_security_group_ingress_rule(args)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 92 def _ec2_security_group_ingress_rule(args) cidr = args[:cidr] || "0.0.0.0/0" cidr_ipv6 = args[:cidr_ipv6] || "" description = _ref_string_default("description", args, '', "inbound rule description") from = _ref_string("from", args) ip = args[:ip] || "tcp" source_group_name = _ref_string("source_group_name", args, "security group") source_group_id = _ref_string("source_group_id", args, "security group") source_group_owner_id = _ref_string("source_group_owner_id", args, "account id") to = _ref_string("to", args) to = from.clone if to.empty? ip = -1 and from = 0 and to = 65535 if ip == "all" _{ CidrIp cidr if source_group_name.empty? and source_group_id.empty? CidrIpv6 cidr_ipv6 unless cidr_ipv6.empty? Description description FromPort from unless ip == "icmp" IpProtocol ip SourceSecurityGroupName source_group_name unless source_group_name.empty? SourceSecurityGroupId source_group_id unless source_group_id.empty? SourceSecurityGroupOwnerId source_group_name unless source_group_owner_id.empty? ToPort to unless ip == "icmp" } end
_ec2_security_group_ingress_rules(name, args)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 76 def _ec2_security_group_ingress_rules(name, args) return [] unless args.key? name.to_sym rules = [] _array(args[name.to_sym]).each do |arg| if arg.is_a? Integer arg = { from: arg, to: arg, } end rules << _ec2_security_group_ingress_rule(arg) end rules end
_ec2_spot_fleet_launches(args)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 277 def _ec2_spot_fleet_launches(args) block_devices = (args[:block_devices] || []).collect{|v| _ec2_block_device(v) } ebs = _bool("ebs", args, false) iam = _ref_string("iam", args, "iam instance profile") iam = _ref_attr_string("iam", "Arn", args, "iam instance profile") if iam.empty? instance_type = _ref_string("instance_type", args, "instance type") image = _ec2_image(args) kernel = args[:kernel] || "" key_name = _ref_string("key_name", args, "key name") monitoring = _bool("monitoring", args, false) network_interfaces = (args[:network_interfaces] || []).collect{|v| _ec2_network_interface_embedded(v, true) } placement = _ref_string("placement", args) ram_disk = args[:ram_disk] || "" security_groups = _ref_array("security_groups", args, "security group") subnet = _ref_string("subnet", args, "subnet") user_data = _ec2_user_data(args) weighted = args[:weighted] || "" _{ BlockDeviceMappings block_devices unless block_devices.empty? EbsOptimized ebs IamInstanceProfile do Arn iam end unless iam.empty? ImageId image InstanceType instance_type KernelId kernel unless kernel.empty? KeyName key_name unless key_name.empty? Monitoring do Enabled monitoring end NetworkInterfaces network_interfaces unless network_interfaces.empty? Placement placement unless placement.empty? RamdiskId ram_disk unless ram_disk.empty? SecurityGroups security_groups unless security_groups.empty? SubnetId subnet unless subnet.empty? UserData user_data unless user_data.empty? WeightedCapacity weighted if args.key? :weighted } end
_ec2_spot_fleet_request(args)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 243 def _ec2_spot_fleet_request(args) allocation = _valid_values(args[:allocation], %w( lowestPrice diversified), "lowestPrice") express = _valid_values(args[:express], %w( noTermination default), "") iam = _ref_attr_string("iam", "Arn", args, "role") # TODO move to role.rb iam = "aws-ec2-spot-fleet-role" if iam.empty? launches = args[:launches].collect{|v| _ec2_spot_fleet_launches(v) } price = args[:price] || 0.00 target = _ref_string("target", args, "") target = 1 if target.empty? terminate = _bool("terminate", args, false) valid_from = (args.key? :valid_from) ? _timestamp_utc(args[:valid_from]) : '' valid_until = if args.key? :valid_until _timestamp_utc(args[:valid_until]) elsif args.key? :valid_from _timestamp_utc(args[:valid_from] + (60 * 60 * 24 * 365)) else '' end _{ AllocationStrategy allocation ExcessCapacityTerminationPolicy express unless express.empty? IamFleetRole iam LaunchSpecifications launches SpotPrice price TargetCapacity target TerminateInstancesWithExpiration terminate ValidFrom valid_from if args.key? :valid_from ValidUntil valid_until if args.key? :valid_from or args.key? :valid_until } end
_ec2_to_block_device_ecs(args)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 6 def _ec2_to_block_device_ecs(args) root_device = { device: "/dev/xvda", delete: _bool("root_delete", args, true), size: args[:root_size] || 8, type: "gp2", } root_device[:ref_size] = "#{args[:ref_root_size]} root" if _ref_key? "root_size", args, '', false # /dev/xvdcz is Docker's use storage data_device = { device: "/dev/xvdcz", delete: _bool("data_delete", args, true), size: args[:data_size], type: "gp2", } data_device[:ref_size] = "#{args[:ref_data_size]} data" if _ref_key? "data_size", args, '', false [ root_device, data_device ] end
_ec2_user_data(args)
click to toggle source
# File lib/kumogata/template/ec2.rb, line 211 def _ec2_user_data(args) if args.key? :user_data user_data = args[:user_data] else user_data = _ref_string("user_data", args, "user data") end return '' if user_data.empty? if user_data.is_a? Hash _base64(user_data) else if user_data.is_a? String if user_data.nil? or user_data.empty? user_data = [] else user_data = [ user_data ] end end if args.key? :ecs # http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-config.html ecs_user_data =<<"EOS" cat <<'EOF' >> /etc/ecs/ecs.config ECS_CLUSTER=#{_name("ecs", args)} EOF EOS user_data = [ecs_user_data] + user_data end _base64_shell(user_data) end end
_ecr_policy(name, args)
click to toggle source
# File lib/kumogata/template/ecr.rb, line 7 def _ecr_policy(name, args) policy = args[name.to_sym] || {} return policy if policy.empty? iam_policy = { service: 'ecr', no_resource: true, } iam_policy[:sid] = policy[:sid] if policy.key? :sid iam_policy[:principal] = policy[:principal] if policy.key? :principal iam_policy[:actions] = policy[:actions] if policy.key? :actions iam_policy[:action] = policy[:action] if policy.key? :action _iam_policy_document('policy', { policy: [ iam_policy ] }) end
_ecs_containers(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 153 def _ecs_containers(args) (args[:containers] || []).collect.with_index do |container, i| container[:name] = "container-#{i + 1}" unless container.key? :name command = _array(container[:command] || []) cpu = container[:cpu] || 1 search_domains = _ref_array("search_domains", args) servers = _ref_array("servers", args) label = container[:label] || {} security_options = _array(container[:security_options] || []) entry_point = _array(container[:entry_point] || []) environment = _pair_name_value(container, "environment") extra_hosts = _ecs_extra_hosts(container) host = _name("host", container) image = if container.key? :my_image _join([ _account_id, ".dkr.ecr.", _region, ".#{DOMAIN}/", container[:my_image], ":", container[:my_image_tag] || "latest" ], "") else container[:image] || "nginx:latest" end links = _array(container[:links] || []) log_config = _ecs_log_configuration(container) memory = container[:memory] || 300 memory_reservation = container[:memory_reservation] || 0 mount_points = _ecs_mount_points(container) port_mappings = _ecs_port_mappings(container) ulimits = _ecs_ulimits(container) user = container[:user] || "" volumes = _ecs_volumes_from(container) working = container[:working] || "" _{ Command command unless command.empty? Cpu cpu DisableNetworking _bool("networking", container, false) DnsSearchDomains search_domains unless search_domains.empty? DnsServers servers unless servers.empty? DockerLabels label unless label.empty? DockerSecurityOptions security_options unless security_options.empty? EntryPoint entry_point unless entry_point.empty? Environment environment unless environment.empty? Essential _bool("essential", container, true) ExtraHosts extra_hosts unless extra_hosts.empty? Hostname host Image image Links links unless links.empty? LogConfiguration log_config unless log_config.empty? Memory memory MemoryReservation memory_reservation if 0 < memory_reservation MountPoints mount_points unless mount_points.empty? Name _ref_string("name", container) PortMappings port_mappings unless port_mappings.empty? Privileged _bool("privileged", container, false) ReadonlyRootFilesystem _bool("read_only", container, false) Ulimits ulimits unless ulimits.empty? User user unless user.empty? VolumesFrom volumes unless volumes.empty? WorkingDirectory working unless working.empty? } end end
_ecs_deployment(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 284 def _ecs_deployment(args) return "" unless args.key? :deployment deployment = args[:deployment] _{ MaximumPercent deployment[:max] || 200 MinimumHealthyPercent deployment[:min] || 50 } end
_ecs_extra_hosts(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 222 def _ecs_extra_hosts(args) (args[:extra_hosts] || []).collect do |host| _{ HostName host[:name] IpAddress host[:ip] } end end
_ecs_load_balancers(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 117 def _ecs_load_balancers(args) (args[:load_balancers] || []).collect do |balancer| target = _ref_string('target', balancer, 'target group') _{ ContainerName _name("name", balancer) ContainerPort balancer[:port] || 80 LoadBalancerName _name("lb_name", balancer) if target.empty? TargetGroupArn target unless target.empty? } end end
_ecs_log_configuration(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 231 def _ecs_log_configuration(args) configuration = args[:log] || [] return configuration if configuration.empty? driver = _valid_values(configuration[:driver], %w( json-file syslog journald gelf fluentd awslogs splunk), "awslogs") option = _ecs_to_log_option(configuration) _{ LogDriver driver Options option unless option.empty? } end
_ecs_mount_points(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 244 def _ecs_mount_points(args) (args[:mount_points] || args[:mounts] || []).collect do |point| _{ ContainerPath point[:path] SourceVolume point[:source] ReadOnly _bool("read_only", point, false) } end end
_ecs_network(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 130 def _ecs_network(args) vpc = args[:vpc] || [] return vpc if vpc.empty? vpc = _ecs_vpc(vpc) _{ AwsvpcConfiguration vpc } end
_ecs_placement_definition(args, key = 'placement')
click to toggle source
# File lib/kumogata/template/ecs.rb, line 295 def _ecs_placement_definition(args, key = 'placement') placement = args[key.to_sym] || [] return placement if placement.empty? type = _valid_values(placement[:type], %w( distinctInstance memberOf), "distinctInstance") expression = placement[:expression] || "" _{ Type type Expression expression unless placement.empty? } end
_ecs_placement_strategies(args, key = 'placement')
click to toggle source
# File lib/kumogata/template/ecs.rb, line 308 def _ecs_placement_strategies(args, key = 'placement') placement = args[key.to_sym] || [] return placement if placement.empty? type = _valid_values(placement[:type], %w( random spread binpack ), "random") field = case type when "binpack" _valid_values(placement[:field], %w( cpu memory ), "cpu") when "spread" args[:field] || "" else "" end _{ Type type Field field unless field.empty? } end
_ecs_port_mappings(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 254 def _ecs_port_mappings(args) (args[:port_mappings] || args[:ports] || []).collect do |port| host = _ref_string("host", port, 'host port') _{ ContainerPort _ref_string("container", port, 'container port') HostPort host unless host.empty? Protocol _valid_values(port[:protocol], %w( tcp udp ), 'tcp') } end end
_ecs_to_log_option(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 6 def _ecs_to_log_option(args) option = case args[:driver] when "awslogs" _ecs_to_log_option_awslogs(args) when "fluentd" _ecs_to_log_option_fluentd(args) when "syslog" _ecs_to_log_option_syslog(args) when "json" _ecs_to_log_option_syslog(args) when "splunk" _ecs_to_log_option_splunk(args) when "gelf" _ecs_to_log_option_gelf(args) else {} end option.merge(_ecs_to_log_option_common(args)) end
_ecs_to_log_option_awslogs(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 27 def _ecs_to_log_option_awslogs(args) { "awslogs-group": args[:group], "awslogs-region": args[:region] || _region, "awslogs-stream-prefix": args[:prefix] || "", } end
_ecs_to_log_option_common(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 94 def _ecs_to_log_option_common(args) option = {} option[:labels] = args[:labels].join(',') if args.key? :labels option[:env] = args[:envs].join(',') if args.key? :envs option["env-regex"] = args[:env_regex] if args.key? :env_regex option[:tag] = args[:tag] if args.key? :tag option end
_ecs_to_log_option_fluentd(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 35 def _ecs_to_log_option_fluentd(args) option = { "fluentd-address": args[:address] || "localhost:24224", "fluentd-retry-wait": args[:retry_wait] || 1, "fluentd-max-retries": args[:max_retries] || 10, } option["fluentd-async-connect"] = true if args.key? :async option["fluentd-buffer-limit"] = args[:buffer_limit] if args.key? :buffer_limit option end
_ecs_to_log_option_gelf(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 85 def _ecs_to_log_option_gelf(args) option = { "gelf-address": args[:address], "gelf-compression-type": args[:type] || "gzip", } option["gelf-compression-level"] = args[:level] if args.key? :level option end
_ecs_to_log_option_json(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 59 def _ecs_to_log_option_json(args) option = { "max-size": args[:max_size] || "10m", "max-file": args[:max_file] || 1, } option end
_ecs_to_log_option_splunk(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 67 def _ecs_to_log_option_splunk(args) option = { "splunk-token": args[:token], "splunk-url": args[:url], "splunk-verify-connection": _bool("veriy_connection", args, true), "splunk-gzip": _bool("gzip", args, false), } option["splunk-source"] = args[:source] if args.key? :source option["splunk-sourcetype"] = args[:source_type] if args.key? :source_type option["splunk-index"] = args[:index] if args.key? :index option["splunk-capath"] = args[:capath] if args.key? :capath option["splunk-caname"] = args[:caname] if args.key? :caname option["splunk-insecureskipverify"] = true if args.key? :skip_verify option["splunk-format"] = args[:format] if args.key? :format option["splunk-gzip-level"] = args[:gzip_level] if args.key? :gzip_label option end
_ecs_to_log_option_syslog(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 46 def _ecs_to_log_option_syslog(args) option = { "syslog-address": args[:address], } option["syslog-facility"] = args[:facility] if args.key? :facility option["syslog-tls-ca-cert"] = args[:ca_cert] if args.key? :ca_cert option["syslog-tls-cert"] = args[:cert] if args.key? :cert option["syslog-tls-key"] = args[:key] if args.key? :key option["syslog-tls-skip-verify"] = true if args.key? :skip_verify option["syslog-format"] = args[:format] if args.key? :format option end
_ecs_ulimits(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 265 def _ecs_ulimits(args) (args[:ulimits] || []).collect do |ulimit| _{ HardLimit ulimit[:hard] Name _name("name", ulimit) SoftLimit ulimit[:hard] || ulimit[:soft] } end end
_ecs_volumes(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 103 def _ecs_volumes(args) (args[:volumes] || []).collect do |volume| volume = { volume: "" } if volume.is_a? String volume.map.collect do |name, source| _{ Name name Host do SourcePath source end unless source.empty? } end end.flatten end
_ecs_volumes_from(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 275 def _ecs_volumes_from(args) (args[:volumes_from] || args[:volumes] || []).collect do |volume| _{ SourceContainer _ref_string("source", volume) ReadOnly _bool("read_only", volume, false) } end end
_ecs_vpc(args)
click to toggle source
# File lib/kumogata/template/ecs.rb, line 141 def _ecs_vpc(args) assign_public = _bool('assign_public', args, false) security_groups = _ref_array('security_groups', args, 'security group') subnets = _ref_array('subnets', args, 'subnets') _{ AssignPublicIp assign_public ? 'ENABLED' : 'DISABLED' SecurityGroups security_groups unless security_groups.empty? Subnets subnets } end
_elasticache_to_engine(args)
click to toggle source
# File lib/kumogata/template/elasticache.rb, line 6 def _elasticache_to_engine(args) _valid_values(args[:engine], %w( memcached redis ), ELASTICACHE_DEFAULT_ENGINE) end
_elasticache_to_node(args)
click to toggle source
# File lib/kumogata/template/elasticache.rb, line 10 def _elasticache_to_node(args) node = _ref_string("node", args, "cache node types") if node.is_a? String node = "cache.#{node}" if node !~ /cache./ node = _valid_values(node, ELASTICACHE_NODE_TYPES, ELASTICACHE_DEFAULT_NODE_TYPE) end node end
_elasticache_to_parameter(args)
click to toggle source
# File lib/kumogata/template/elasticache.rb, line 19 def _elasticache_to_parameter(args) engine = _elasticache_to_engine(args) parameter = _ref_string("parameter", args, "cache parameter group") if parameter.empty? if engine == "memcached" parameter = "default.memcached1.4" else parameter = "default.redis2.8" end end parameter end
_elasticbeanstalk_configuration(configuration)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 937 def _elasticbeanstalk_configuration(configuration) _{ ApplicationName configuration[:application] TemplateName configuration[:template] } end
_elasticbeanstalk_options(options)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 927 def _elasticbeanstalk_options(options) options.collect do |option| _{ Namespace option[:name] OptionName option[:option] Value option[:value] } end end
_elasticbeanstalk_tier(tier)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 944 def _elasticbeanstalk_tier(tier) if tier.is_a? String case tier.downcase when "web", "webserver" name = "WebServer" when "work", "worker" name = "Worker" else name = "WebServer" end tier = { name: name } end name = _valid_values(tier[:name], %w( WebServer Worker ), "WebServer") _{ Name name Type (name == "WebServer") ? "Standard" : "SQS/HTTP" Version tier[:version] || "1.0" } end
_elasticbeanstalk_to_option_application(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 274 def _elasticbeanstalk_to_option_application(args) array = [] array << { name: "aws:elasticbeanstalk:application", option: "ApplicationHealthcheckURL", value: args[:health_check], } if args.key? :health_check array end
_elasticbeanstalk_to_option_application_environment(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 284 def _elasticbeanstalk_to_option_application_environment(args) args.collect do |k, v| { name: "aws:elasticbeanstalk:application:environment", option: k, value: v, } end end
_elasticbeanstalk_to_option_asg(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 8 def _elasticbeanstalk_to_option_asg(args) array = [] array << { name: "aws:autoscaling:asg", option: "AvailabilityZone", value: args[:az], } if args.key? :az array << { name: "aws:autoscaling:asg", option: "Cooldown", value: args[:cooldown] || 360, } array << { name: "aws:autoscaling:asg", option: "CusotomAvailabilityZones", value: _ref_array("custuom_az"), } if args.key? :custom_az array << { name: "aws:autoscaling:asg", option: "MinSize", value: args[:min_size] || 1, } array << { name: "aws:autoscaling:asg", option: "MaxSize", value: args[:max_size] || 4, } array end
_elasticbeanstalk_to_option_command(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 315 def _elasticbeanstalk_to_option_command(args) array = [] array << { name: "aws:elasticbeanstalk:command", option: "DeploymentPolicy", value: _valid_values(args[:deployment], %w( AllAtOnce Rolling RollingWithAdditionalBatch Immutable ), "AllAtOnce"), } array << { name: "aws:elasticbeanstalk:command", option: "Timeout", value: args[:timeout] || 600, # 1 to 3600 } array << { name: "aws:elasticbeanstalk:command", option: "BatchSizeType", value: _valid_values(args[:batch_size_type], %w( Percentage Fixed ), "Percentage"), } array << { name: "aws:elasticbeanstalk:command", option: "BatchSize", value: args[:batch_size] || 1, # Percentage: 1 to 100, Fixed: 1 to aws:autoscaling:MaxSize } array << { name: "aws:elasticbeanstalk:command", option: "IgnoreHealthCheck", value: _bool("ignore_health_check", args, false), } array << { name: "aws:elasticbeanstalk:command", option: "HealthCheckSuccessThreshold", value: _valid_values(args[:health_check_success], %w( Ok Warning Degraded Severe ), "Ok"), } array end
_elasticbeanstalk_to_option_elb_health_check(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 586 def _elasticbeanstalk_to_option_elb_health_check(args) array = [] array << { name: "aws:elb:healthcheck", option: "HealthyThreshold", value: args[:healthy] || 3, # 2 to 10 } array << { name: "aws:elb:healthcheck", option: "Interval", value: args[:interval] || 10, # 5 to 300 } array << { name: "aws:elb:healthcheck", option: "Timeout", value: args[:timeout] || 5, # 2 to 60 } array << { name: "aws:elb:healthcheck", option: "UnhealthyThreshold", value: args[:unhealthy] || 5, # 2 to 10 } array end
_elasticbeanstalk_to_option_elb_listener(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 631 def _elasticbeanstalk_to_option_elb_listener(args) array = [] array << { name: "aws:elb:listener", option: "ListenerProtocol", value: _valid_values(args[:protocol], %w( HTTP TCP ), "HTTP"), } array << { name: "aws:elb:listener", option: "InstancePort", value: args[:instance_port] || 80, # 1 to 65535 } if args.key? :instance_port array << { name: "aws:elb:listener", option: "InstanceProtocol", value: args[:instance_protocol], } array << { name: "aws:elb:listener", option: "PolicyNames", value: args[:policy_names], } if args.key? :policy_names array << { name: "aws:elb:listener", option: "ListenerEnabled", value: _bool("enabled", args, true), } array end
_elasticbeanstalk_to_option_elb_listener_port(args, port)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 661 def _elasticbeanstalk_to_option_elb_listener_port(args, port) array = [] array << { name: "aws:elb:listener:#{port}", option: "ListenerProtocol", value: _valid_values(args[:protocol], %w( HTTP TCP ), "HTTP"), } array << { name: "aws:elb:listener:#{port}", option: "InstancePort", value: args[:instance_port] || 80, # 1 to 65535 } if args.key? :instance_port array << { name: "aws:elb:listener:#{port}", option: "InstanceProtocol", value: args[:instance_protocol], } array << { name: "aws:elb:listener:#{port}", option: "PolicyNames", value: args[:policy_names], } if args.key? :policy_names array << { name: "aws:elb:listener:#{port}", option: "SSLCertificateId", value: args[:ssl_certificate], } if args.key? :ssl_cretificate array << { name: "aws:elb:listener:#{port}", option: "ListenerEnabled", value: _bool("enabled", args, true), } array end
_elasticbeanstalk_to_option_elb_loadbalancer(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 611 def _elasticbeanstalk_to_option_elb_loadbalancer(args) array = [] array << { name: "aws:elb:loadbalancer", option: "CrossZone", value: _bool("cross", args, true), } array << { name: "aws:elb:loadbalancer", option: "SecurityGroups", value: _join(_ref_array("security_groups", args)), } array << { name: "aws:elb:loadbalancer", option: "ManagedSecurityGroup", value: args[:managed_security_group], } if args.key? :managed_security_group array end
_elasticbeanstalk_to_option_elb_policies(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 696 def _elasticbeanstalk_to_option_elb_policies(args) array = [] array << { name: "aws:elb:policies", option: "ConnectionDrainingEnabled", value: _bool("connection_draining_enabled", args, false), } array << { name: "aws:elb:policies", option: "ConnectionDrainingTimeout", value: args[:connection_draining_timeout] || 20, # 1 to 3600 } array << { name: "aws:elb:policies", option: "ConnectionSettingIdleTimeout", value: args[:connection_draining_idle], # 1 to 3600 } array << { name: "aws:elb:policies", option: "LoadBalancerPorts", value: args[:load_balancer_ports], } if args.key? :load_balancer_ports array << { name: "aws:elb:policies", option: "Stickiness Cookie Expiration", value: args[:stickiness_cookie_expiration], # 0 to 1000000 } if args.key? :stickiness_cookie_expiration array << { name: "aws:elb:policies", option: "Stickiness Policy", value: _bool("stickiness_policy", args, false), } array end
_elasticbeanstalk_to_option_elb_policy_name(args, name)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 731 def _elasticbeanstalk_to_option_elb_policy_name(args, name) array = [] array << { name: "aws:elb:policies:#{name}", option: "CookieName", value: args[:cookie_name], } if args.key? :cookie_name array << { name: "aws:elb:policies:#{name}", option: "InstancePorts", value: args[:instance_ports], } if args.key? :instance_ports array << { name: "aws:elb:policies:#{name}", option: "LoadBalancerPorts", value: args[:load_balancer_ports], } if args.key? :load_balancer_ports array << { name: "aws:elb:policies:#{name}", option: "ProxyProtocol", value: args[:proxy_protocol], } if args.key? :proxy_protocol array << { name: "aws:elb:policies:#{name}", option: "PublicKey", value: args[:public_key], } if args.key? :public_key array << { name: "aws:elb:policies:#{name}", option: "PublicKeyPolicyNames", value: args[:public_key_policy_names], } if args.key? :public_key_policy_names array << { name: "aws:elb:policies:#{name}", option: "SSLProtocols", value: args[:ssl_protocols], } if args.key? :ssl_protocols array << { name: "aws:elb:policies:#{name}", option: "SSLReferencePolicy", value: args[:ssl_reference], } if args.key? :ssl_reference array << { name: "aws:elb:policies:#{name}", option: "Stickiness Cookie Expiration", value: args[:stickiness_cookie_expiration], # 0 to 1000000 } if args.key? :stickiness_cookie_expiration array << { name: "aws:elb:policies:#{name}", option: "Stickiness Policy", value: _bool("stickiness_policy", args, false), } array end
_elasticbeanstalk_to_option_elbv2_listener(args, name = "default")
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 786 def _elasticbeanstalk_to_option_elbv2_listener(args, name = "default") array = [] array << { name: "aws:elbv2:listener:#{name}", option: "DefaultProcess", value: args[:process] || "default", } array << { name: "aws:elbv2:listener:#{name}", option: "ListenerEnabled", value: _bool("enabled", args, true), } array << { name: "aws:elbv2:listener:#{name}", option: "Rules", value: _join(args[:rules]), } if args.key? :rules if name != "default" array << { name: "aws:elbv2:listener:listener_port", option: "SSLCertificateArns", value: args[:ssl_certificate_arns], } if args.key? :ssl_certificate_arns array << { name: "aws:elbv2:listener:listener_port", option: "SSLPolicy", value: args[:ssl_policy], } if args.key? :ssl_policy end array end
_elasticbeanstalk_to_option_elbv2_listener_rule(args, name)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 818 def _elasticbeanstalk_to_option_elbv2_listener_rule(args, name) array = [] array << { name: "aws:elbv2:listenerrule:#{name}", option: "PathPatterns", value: args[:path], } if args.key? :path array << { name: "aws:elbv2:listenerrule:#{name}", option: "Priority", value: args[:priority] || 1, # 1 to 1000 } array << { name: "aws:elbv2:listenerrule:#{name}", option: "Process", value: args[:process] || "default", } array end
_elasticbeanstalk_to_option_elbv2_load_balancer(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 838 def _elasticbeanstalk_to_option_elbv2_load_balancer(args) array = [] array << { name: "aws:elbv2:loadbalancer", option: "AccessLogsS3Bucket", value: args[:access_logs_s3_bucket], } if args.key? :access_logs_s3_bucket array << { name: "aws:elbv2:loadbalancer", option: "AccessLogsS3Enabled", value: _bool("access_logs_s3", args, false), } array << { name: "aws:elbv2:loadbalancer", option: "AccessLogsS3Prefix", value: args[:access_logs_s3_prefix], } if args.key? :access_logs_s3_prefix array << { name: "aws:elbv2:loadbalancer", option: "IdleTimeout", value: args[:idle_timeout], } if args.key? :idle_timeout array << { name: "aws:elbv2:loadbalancer", option: "ManagedSecurityGroup", value: args[:managed_security_group], } if args.key? :managed_security_group array << { name: "aws:elbv2:loadbalancer", option: "SecurityGroups", value: _join(_ref_array("security_groups", args)), } end
_elasticbeanstalk_to_option_environment(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 354 def _elasticbeanstalk_to_option_environment(args) array = [] array << { name: "aws:elasticbeanstalk:environment", option: "EnvironmentType", value: _valid_values(args[:type], %w( SingleInstance LoadBalanced ), "LoadBalanced"), } array << { name: "aws:elasticbeanstalk:environment", option: "ServiceRole", value: args[:service_role] || "aws-elasticbeanstalk-service-role", } array << { name: "aws:elasticbeanstalk:environment", option: "LoadBalancerType", value: _valid_values(args[:load_balancer_type], %w( classic application ), "application") } if args.key? :load_balancer_type array end
_elasticbeanstalk_to_option_healthreporting_system(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 441 def _elasticbeanstalk_to_option_healthreporting_system(args) array = [] array << { name: "aws:elasticbeanstalk:healthreporting:system", option: "SystemType", value: _valid_values(args[:type], %w( basic enhanced ), "basic"), } array << { name: "aws:elasticbeanstalk:healthreporting:system", option: "ConfigDocument", value: args[:config], } if args.key? :config array end
_elasticbeanstalk_to_option_host_manager(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 456 def _elasticbeanstalk_to_option_host_manager(args) array = [] array << { name: "aws:elasticbeanstalk:hostmanager", option: "LogPublicationControl", value: _bool("log_publication", args, false), } array end
_elasticbeanstalk_to_option_launch_configuration(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 38 def _elasticbeanstalk_to_option_launch_configuration(args) array = [] array << { name: "aws:autoscaling:launchconfiguration", option: "EC2KeyName", value: _ref_string("key_name", args), } array << { name: "aws:autoscaling:launchconfiguration", option: "IamInstanceProfile", value: _ref_string_default("instance_profile", args, '', ELASTIC_BEANTALK_EC2_DEFAULT_ROLE), } array << { name: "aws:autoscaling:launchconfiguration", option: "ImageId", value: _ref_string("image_id", args), } if args.key? :image_id array << { name: "aws:autoscaling:launchconfiguration", option: "InstanceType", value: _ref_string_default("instance_type", args, '', EC2_DEFAULT_INSTANCE_TYPE), } array << { name: "aws:autoscaling:launchconfiguration", option: "MonitoringInterval", value: args[:monitoring] || "5 minute", } array << { name: "aws:autoscaling:launchconfiguration", option: "SecurityGroups", value: _join(_ref_array("security_groups", args)), } if _ref_key?("security_groups", args) array << { name: "aws:autoscaling:launchconfiguration", option: "SSHSourceRestriction", value: args[:ssh_source], } if args.key? :ssh_source array << { name: "aws:autoscaling:launchconfiguration", option: "BlockDeviceMappings", value: args[:block_devices].collect{|v| _ec2_block_device(v) }, } if _ref_key?(:block_devices, args) array << { name: "aws:autoscaling:launchconfiguration", option: "RootVolumeType", value: _ref_string_default("root_volume_type", args, '', 'gp2'), } array << { name: "aws:autoscaling:launchconfiguration", option: "RootVolumeSize", #ref_root_volume_size value: _ref_string_default("root_volume_size", args, '', 10), } array << { name: "aws:autoscaling:launchconfiguration", option: "RootVolumeIOPS", value: _ref_string("root_volume_iops", args), } if _ref_key?("root_volume_iops", args) array end
_elasticbeanstalk_to_option_logs(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 294 def _elasticbeanstalk_to_option_logs(args) array = [] array << { name: "aws:elasticbeanstalk:cloudwatch:logs", option: "StreamLogs", value: _bool("stream", args, false), } array << { name: "aws:elasticbeanstalk:cloudwatch:logs", option: "DeleteOnTerminate", value: _bool("terminate", args, false), } array << { name: "aws:elasticbeanstalk:cloudwatch:logs", option: "RetentionInDays", value: _valid_values(args[:rentetion], %w( 1 3 7 14 30 60 90 120 150 180 365 400 545 731 1827 3653 )), } array end
_elasticbeanstalk_to_option_managed_actions(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 466 def _elasticbeanstalk_to_option_managed_actions(args) array = [] array << { name: "aws:elasticbeanstalk:managedactions", option: "ManagedActionsEnabled", value: _bool("enabled", args, false), } array << { name: "aws:elasticbeanstalk:managedactions", option: "PreferredStartTime", value: args[:time].utc.strftime("%a:%H:%M"), } if args.key? :time array end
_elasticbeanstalk_to_option_monitoring(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 496 def _elasticbeanstalk_to_option_monitoring(args) array = [] array << { name: "aws:elasticbeanstalk:managedactions:monitoring", option: "Automatically Terminate Unhealthy Instances", value: _bool("automatically", args, true), } array end
_elasticbeanstalk_to_option_platform_update(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 481 def _elasticbeanstalk_to_option_platform_update(args) array = [] array << { name: "aws:elasticbeanstalk:managedactions:platformupdate", option: "UpdateLevel", value: args[:level], } if args.key? :level array << { name: "aws:elasticbeanstalk:managedactions:platformupdate", option: "InstanceRefreshEnabled", value: _bool("enabled", args, false), } array end
_elasticbeanstalk_to_option_process(args, name = "default")
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 376 def _elasticbeanstalk_to_option_process(args, name = "default") array = [] array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "DeregistrationDelay", value: args[:deregistration] || 20, # 0 to 3600 } array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "HealthCheckInterval", value: args[:health_chek_interval] || 15, # 15 to 300 } array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "HealthCheckPath", value: args[:health_check_path] || "/", } array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "HealthCheckTimeout", value: args[:health_check_timeout] || 5, # 1 to 60 } array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "HealthyThresholdCount", value: args[:healthy] || 3, # 1 to 10 } array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "MatcherHTTPCode", value: args[:matcher_http] || 200, # 200 to 399 } array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "Port", value: args[:port] || 80, # 1 to 65535 } array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "Protocol", value: _valid_values(args[:protocol], %w( HTTP HTTPS ), "HTTP"), } array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "StickinessEnabled", value: _bool("stickiness_enabled", args, false), } array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "StickinessLBCookieDuration", value: args[:stickiness_lb_cookie_duration] || 86400, # 1 to 604800 } array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "StickinessType", value: "lb_cookie", } if args.key? :stickiness_type array << { name: "aws:elasticbeanstalk:environment:process:#{name}", option: "UnhealthyThresholdCount", value: args[:uhealth] || 5, # 2 to 10 } array end
_elasticbeanstalk_to_option_rds_db_instance(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 872 def _elasticbeanstalk_to_option_rds_db_instance(args) array = [] array << { name: "aws:rds:dbinstance", option: "DBAllocatedStorage", value: args[:allocated_storage], # MySQL:5-1024 } if args.key? :allocated_storage array << { name: "aws:rds:dbinstance", option: "DBDeletionPolicy", value: _valid_values(args[:deletion_policy], %w( Delete Snapshot ), "Delete"), } array << { name: "aws:rds:dbinstance", option: "DBEngine", value: _valid_values(args[:engine], %w( mysql oracle-se1 oracle-se oracle-ee sqlserver-ee sql-server-ex sqlserver-web sqlserver-se postgres ), "mysql"), } array << { name: "aws:rds:dbinstance", option: "DBEngineVersion", value: args[:engine_version] || "5.7", } array << { name: "aws:rds:dbinstance", option: "DBInstanceClass", value: _valid_values(args[:instance_class], RDS_INSTANCE_CLASSES, RDS_DEFAULT_INSTANCE_CLASS), } array << { name: "aws:rds:dbinstance", option: "DBPassword", value: args[:password], } if args.key? :password array << { name: "aws:rds:dbinstance", option: "DBSnapshotIdentifier", value: args[:snapshot], } if args.key? :snapshot array << { name: "aws:rds:dbinstance", option: "DBUser", value: args[:user] || "ebroot", } array << { name: "aws:rds:dbinstance", option: "MultiAZDatabase", value: _bool("multi_az", args, false), } array end
_elasticbeanstalk_to_option_scheduled_action(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 101 def _elasticbeanstalk_to_option_scheduled_action(args) array = [] array << { name: "aws:autoscaling:scheduledaction", option: "DesiredCapacity", value: args[:desired], } if args.key? :desired array << { name: "aws:autoscaling:scheduledaction", option: "EndTime", value: _time_utc(args[:end_time]), } if args.key? :end_time array << { name: "aws:autoscaling:scheduledaction", option: "MaxSize", value: args[:max_size], } if args.key? :max_size array << { name: "aws:autoscaling:scheduledaction", option: "MinSize", value: args[:min_size], } if args.key? :min_size array << { name: "aws:autoscaling:scheduledaction", option: "Recurrence", value: _autoscaling_to_schedued_recurrence(args[:recurrence]), } if args.key? :recurrence array << { name: "aws:autoscaling:scheduledaction", option: "StartTime", value: _time_utc(args[:start_time]), } if args.key? :start_time array << { name: "aws:autoscaling:scheduledaction", option: "Suspend", value: _bool("suspend", args, false), } if args.key? :suspend array end
_elasticbeanstalk_to_option_sns_topics(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 506 def _elasticbeanstalk_to_option_sns_topics(args) array = [] array << { name: "aws:elasticbeanstalk:sns:topics", option: "Notification Endpoint", value: args[:endpoint], } if args.key? :endpoint array << { name: "aws:elasticbeanstalk:sns:topics", option: "Notification Protocol", value: _sns_to_protocol(args[:protocol]), } array << { name: "aws:elasticbeanstalk:sns:topics", option: "Notification Topic ARN", value: args[:topic_arn], } if args.key? :topic_arn array << { name: "aws:elasticbeanstalk:sns:topics", option: "Notification Topic Name", value: args[:topic_name], } if args.key? :topic_name array end
_elasticbeanstalk_to_option_sqsd(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 531 def _elasticbeanstalk_to_option_sqsd(args) array = [] array << { name: "aws:elasticbeanstalk:sqsd", option: "WorkerQueueURL", value: args[:worker_queue_url], } if args.key? :worker_queue_url array << { name: "aws:elasticbeanstalk:sqsd", option: "HttpPath", value: args[:http_path] || "/", } array << { name: "aws:elasticbeanstalk:sqsd", option: "MimeType", value: args[:mime_type], } if args.key? :mime_type array << { name: "aws:elasticbeanstalk:sqsd", option: "HttpConnections", value: args[:http_connections] || 15, # 1 to 100 } array << { name: "aws:elasticbeanstalk:sqsd", option: "ConnectTimeout", value: args[:connect_timeout] || 5, # 1 to 60 } array << { name: "aws:elasticbeanstalk:sqsd", option: "InactivityTimeout", value: args[:inactivity_timeout] || 180, # 1 to 1800 } array << { name: "aws:elasticbeanstalk:sqsd", option: "VisibilityTimeout", value: args[:visibility_timeout] || 300, # 0 to 43200 } array << { name: "aws:elasticbeanstalk:sqsd", option: "ErrorVisibilityTimeout", value: args[:error_visibility_timeout] || 300, # 0 to 43200 } array << { name: "aws:elasticbeanstalk:sqsd", option: "RetentionPeriod", value: args[:retention] || 345600, # 60 to 1209600 } array << { name: "aws:elasticbeanstalk:sqsd", option: "MaxRetries", value: args[:max_retries] || 10, # 1 to 100 } array end
_elasticbeanstalk_to_option_trigger(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 141 def _elasticbeanstalk_to_option_trigger(args) array = [] array << { name: "aws:autoscaling:trigger", option: "BreachDuration", value: args[:breach_duration] || 5, # 1 to 600 } array << { name: "aws:autoscaling:trigger", option: "LowerBreachScaleIncrement", value: args[:lower_breach] || -2, } array << { name: "aws:autoscaling:trigger", option: "LowerThreshold", value: args[:lower_threshold] || 200000, # 0 to 20000000 } array << { name: "aws:autoscaling:trigger", option: "MeasureName", value: _valid_values(args[:measure], %w( CPUUtilization NetworkIn NetworkOut DiskWriteBytes DiskWriteOps DiskReadBytes DiskReadOps Latency RequestCount HealthyHostCount UnhealthyHostCount ), "NetworkOut"), } array << { name: "aws:autoscaling:trigger", option: "Period", value: args[:period] || 5, } array << { name: "aws:autoscaling:trigger", option: "Statistic", value: _valid_values(args[:statistic], %w( Minimum Maximum Sum Average ), "Average") } array << { name: "aws:autoscaling:trigger", option: "Unit", value: _valid_values(args[:unit], %w( Seconds Percent Bytes Bits Count Bytes/Second Bits/Second Count/Second None ), "Bytes"), } array << { name: "aws:autoscaling:trigger", option: "UpperThreshold", value: args[:upper_breach] || 1, } array << { name: "aws:autoscaling:trigger", option: "UpperThreshold", value: args[:lower_threshold] || 6000000, # 0 to 20000000 } array end
_elasticbeanstalk_to_option_vpc(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 239 def _elasticbeanstalk_to_option_vpc(args) array = [] array << { name: "aws:ec2:vpc", option: "VpcId", value: _ref_string("vpc", args, "vpc"), } array << { name: "aws:ec2:vpc", option: "Subnets", value: _join(_ref_array("subnets", args)), } array << { name: "aws:ec2:vpc", option: "ELBSubnets", value: _join(_ref_array("elb_subnets", args)), } if args.key? :elb array << { name: "aws:ec2:vpc", option: "ELBScheme", value: "internal", } if args.key? :elb array << { name: "aws:ec2:vpc", option: "DBSubnets", valiue: _join(_ref_array("db_subnets", args)), } if args.key? :db array << { name: "aws:ec2:vpc", option: "AssociatePublicIpAddress", value: _bool("is_public", args), } if args.key :is_public array end
_elasticbeanstalk_to_rolling_update(args)
click to toggle source
# File lib/kumogata/template/elasticbeanstalk.rb, line 200 def _elasticbeanstalk_to_rolling_update(args) array = [] array << { name: "aws:autoscaling:updatepolicy:rollingupdate", option: "MaxBatchSize", value: args[:max_batch_size], # 1 to 10000 } if args.key? :max_batch_size array << { name: "aws:autoscaling:updatepolicy:rollingupdate", option: "MinInstanceInService", value: args[:min_instance], # 0 to 9999 } if args.key? :min_instance array << { name: "aws:autoscaling:updatepolicy:rollingupdate", option: "RollingUpdateEnabled", value: _bool("enabled", args, false), } array << { name: "aws:autoscaling:updatepolicy:rollingupdate", option: "RollingUpdateType", value: _valid_values(args[:type], %w( Time Health Immutable ), "Time"), } array << { name: "aws:autoscaling:updatepolicy:rollingupdate", option: "PauseTime", value: _timestamp_utc_duration(args[:pause_time][:minute], args[:pause_time][:hour], args[:pause_time][:second]), } if args.key? :pause_time array << { name: "aws:autoscaling:updatepolicy:rollingupdate", option: "Timeout", value: _timestamp_utc_duration(args[:timeout][:minute], args[:timeout][:hour], args[:timeout][:second]) } if args.key? :timeout array end
_elb_access_logging_policy(args)
click to toggle source
# File lib/kumogata/template/elb.rb, line 6 def _elb_access_logging_policy(args) access = args[:access_logging] || "" return "" if access.empty? _{ EmitInterval access[:emit] || 5 Enabled _bool("enabled", access, true) S3BucketName access[:s3_bucket] S3BucketPrefix access[:s3_bucket_prefix] } end
_elb_connection_draining_policy(args)
click to toggle source
# File lib/kumogata/template/elb.rb, line 27 def _elb_connection_draining_policy(args) connection = args[:connection_draining] || {} _{ Enabled _bool("enabled", connection, true) Timeout connection[:timeout] || 60 } end
_elb_connection_settings(args)
click to toggle source
# File lib/kumogata/template/elb.rb, line 36 def _elb_connection_settings(args) connection = args[:connection_settings] || {} _{ IdleTimeout connection[:idle] || 60 } end
_elb_health_check(args)
click to toggle source
# File lib/kumogata/template/elb.rb, line 44 def _elb_health_check(args) health_check = args[:health_check] || {} protocol = _valid_values(health_check[:protocol], %w( http https tcp ssl ), "http") port = health_check[:port] || case protocol when "http" 80 when "https" 443 end path = health_check[:path] || "index.html" _{ HealthyThreshold health_check[:healthy] || 10 Interval health_check[:interval] || 30 Target "#{protocol.upcase}:#{port}/#{path}" Timeout health_check[:timeout] || 5 UnhealthyThreshold health_check[:unhealthly] || 2 } end
_elb_listeners(args)
click to toggle source
# File lib/kumogata/template/elb.rb, line 72 def _elb_listeners(args) listeners = args[:listeners] || [] listeners = [ { protocol: "http" } ] if listeners.empty? listeners.collect do |listener| proto = listener[:protocol] || "http" protocol = _valid_values(proto, %w( http https tcp ssl ), "http") lb_port = case protocol when "http" 80 when "https" 443 end instance_proto = listener[:instance_protocol] || protocol instance_protocol = _valid_values(instance_proto, %w( http https tcp ssl ), "http") instance_port = case instance_protocol when "http" 80 when "https" 443 end policies = [] if protocol == "https" or protocol == "ssl" policy = listener[:policy] || "2016-08" policies << "ELBSecurityPolicy-#{policy}" end ssl = _ref_string("ssl", listener) _{ InstancePort instance_port InstanceProtocol instance_protocol.upcase LoadBalancerPort lb_port PolicyNames policies unless policies.empty? Protocol protocol.upcase SSLCertificateId ssl if protocol == "https" } end end
_elb_policy_types(args)
click to toggle source
# File lib/kumogata/template/elb.rb, line 113 def _elb_policy_types(args) (args[:policy] || []).collect do |policy| attributes = [] instance_ports = [] lb_ports = [] policy_name = policy[:name] policy_type = policy[:type] _{ Attributes attributes unless attributes.empty? InstancePorts instance_ports unless instance_ports.empty? LoadBalancerPorts lb_ports unless lb_ports.empty? PolicyName policy_name PolicyType policy_type } end end
_emr_applications(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 45 def _emr_applications(args) applications = args[:applications] || [] applications.collect do |application| args = application[:args] || [] _{ #AdditionalInfo Args args unless args.empty? Name application[:name].capitalize Version application[:version] if application.key? :version } end end
_emr_bootstraps(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 59 def _emr_bootstraps(args) actions = args[:bootstraps] || [] actions.collect do |action| _{ Name action[:name] ScriptBootstrapAction _{ Args action[:script_args] if action.key? :script_args Path action[:script_path] } } end end
_emr_configurations(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 73 def _emr_configurations(args) configurations = args[:configurations] || [] configurations.collect do |configuration| classification = configuration[:classification] || "" properties = configuration[:properties] || {} configurations = _emr_configurations(configuration) _{ Classification classification unless classification.empty? ConfigurationProperties properties Configurations configurations } end end
_emr_ebs(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 88 def _emr_ebs(args) ebs = args[:ebs] || [] return '' if ebs.empty? block_devices = ebs.collect{|v| _emr_ebs_block_device(v) } _{ EbsBlockDeviceConfig block_devices EbsOptimized true if args.key? :ebs_optimized } end
_emr_ebs_block_device(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 99 def _emr_ebs_block_device(args) volume_spec = _emr_ebs_volume(args) volume_per_instance = args[:per_instance] || "" _{ VolumeSpecification volume_spec VolumesPerInstance volume_per_instance unless volume_per_instance.empty? } end
_emr_ebs_volume(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 109 def _emr_ebs_volume(args) iops = args[:iops] || 300 size = _ref_string("size", args, "volume size") type = _valid_values(args[:type], %w( io1 gp2 sc1 st1 ), "gp2") _{ Iops iops if type == "io1" SizeInGB size VolumeType type } end
_emr_hadoop_jar_step_config(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 241 def _emr_hadoop_jar_step_config(args) config_args = args[:args] || [] jar = args[:jar] main_class = args[:main_class] || "" step_properties = _pair_value(args, "step") _{ Args config_args unless config_args.empty? Jar jar MainClass main_class unless main_class.empty? StepProperties step_properties unless step_properties.empty? } end
_emr_instance_autoscaling(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 255 def _emr_instance_autoscaling(args) autoscaling = args[:autoscaling] || "" return "" if autoscaling.empty? rules = _emr_instance_autoscaling_rules(autoscaling) _{ Constraints do MaxCapacity autoscaling[:max] MinCapacity autoscaling[:min] end Rules rules } end
_emr_instance_autoscaling_rule_action(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 287 def _emr_instance_autoscaling_rule_action(args) market = _valid_values(args[:market] || "", %w( on_demand, spot), "on_demand") simple = _emr_instance_autoscaling_rule_action_simple(args) _{ Market market.upcase SimpleScalingPolicyConfiguration simple } end
_emr_instance_autoscaling_rule_action_simple(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 297 def _emr_instance_autoscaling_rule_action_simple(args) adjustment = case args[:type] when "change" "CHANGE_IN_CAPACITY" when "percent" "PERCENT_CHANGE_IN_CAPACITY" when "exact" "EXACT_CAPACITY" else "CHANGE_IN_CAPACITY" end cool = args[:cool] || 0 scaling = args[:scaling] _{ AdjustmentType adjustment CoolDown cool ScalingAdjustment scaling } end
_emr_instance_autoscaling_rule_trigger(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 319 def _emr_instance_autoscaling_rule_trigger(args) operator = case args[:operator] when ">=" "GREATER_THAN_OR_EQUAL" when ">" "GREATER_THAN" when "<" "LESS_THAN" when "<=" "LESS_THAN_OR_EQUAL" else "GREATER_THAN_OR_EQUAL" end dimensions = _pair_value(args, "dimensions") evaluation = args[:evaluation] || 1 name = _name("definition", args) ns = args[:ns] || "AWS/ElasticMapReduce" period = args[:period] || 300 statistic = _valid_values(args[:statistic], %w( sample_count average sum minimum maximum ), "average") threshold = args[:threshold] unit = _cloudwatch_to_unit(args[:unit]) _{ CloudWatchAlarmDefinition do ComparisonOperator operator Dimensions dimensions unless dimensions.empty? EvaluationPeriods evaluation MetricName name Namespace ns Period period Statistic statistic.upcase Threshold threshold Unit unit end } end
_emr_instance_autoscaling_rules(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 270 def _emr_instance_autoscaling_rules(args) rules = args[:rules] || [] rules.collect do |rule| action = _emr_instance_autoscaling_rule_action(rule) name = _name("rule", rule) description = _ref_string_default("description", rule, '', "#{name} instance autoscaling rules description") trigger = _emr_instance_autoscaling_rule_trigger(rule) _{ Action action Description description Name name Trigger trigger } end end
_emr_instance_fleet(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 159 def _emr_instance_fleet(args) fleet = args[:fleet] || "" return fleet if fleet.empty? configs = _emr_instance_fleet_type_config(fleet) launch = _emr_instance_fleet_launch(fleet) name = _name("fleet", fleet) on_demand = fleet[:on_demand] || 1 spot = fleet[:spot] || 1 _{ InstanceTypeConfigs configs LaunchSpecifications do SpotSpecification launch end unless launch.empty? Name name TargetOnDemandCapacity on_demand TargetSpotCapacity spot } end
_emr_instance_fleet_launch(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 200 def _emr_instance_fleet_launch(args) launch = args[:launch] || "" return launch if launch.empty? block = _valid_values(launch[:block], %w( 60 120 180 240 300 360 ), "") timeout_action = case launch[:timeout_action] when "switch" "SWITCH_TO_ON_DEMAND" when "terminate" "TERMINATE_CLUSTER" else "SWITCH_TO_ON_DEMAND" end timeout_duration = launch[:timeout_duration] || 5 _{ BlockDurationMinutes block unless block.empty? TimeoutAction timeout_action.upcase TimeoutDurationMinutes timeout_duration } end
_emr_instance_fleet_type_config(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 180 def _emr_instance_fleet_type_config(args) (args[:configs] || []).collect do |config| bid = config[:bid] || 0 bid_percent = config[:bid_percent] || "" configurations = _emr_configurations(config) ebs = _emr_ebs(config) instance_type = _ref_string_default("instance_type", args, "instance type", EMR_DEFAULT_INSTANCE_TYPE) weighted = config[:weighted] || 1 _{ BidPrice bid if 0 < bid BidPriceAsPercentageOfOnDemandPrice bid_percent unless bid_percent.empty? Configurations configurations unless configurations.empty? EbsConfiguration ebs unless ebs.empty? InstanceType instance_type WeightedCapacity weighted } end end
_emr_instance_group(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 223 def _emr_instance_group(args) bid = args[:bid] || "" configurations = _emr_configurations(args) instance_count = args[:instance_count] || 1 instance_type = _ref_string_default("instance_type", args, "instance type", EMR_DEFAULT_INSTANCE_TYPE) market = _valid_values("market", %w( on_demand, spot), "on_demand") name = _ref_string("name", args) _{ BidPrice bid unless bid.empty? Configurations configurations unless configurations.empty? InstanceCount instance_count InstanceType instance_type Market market.upcase Name name } end
_emr_job_flow(args)
click to toggle source
# File lib/kumogata/template/emr.rb, line 121 def _emr_job_flow(args) job = args[:job] || {} add_master_security_groups = _ref_array("add_master_security_groups", job, "security group") add_slave_security_groups = _ref_array("add_slave_security_groups", job, "security group") core_instance_fleet = _emr_instance_fleet(job[:core]) core_instance_group = _emr_instance_group(job[:core]) key_name = _ref_string("key_name", job, "key name") subnet = _ref_string("subnet", job, "subnet") emr_master_security_group = _ref_string("emr_master_security_group", job, "security group") emr_slave_security_group = _ref_string("emr_slave_security_group", job, "security group") hadoop_version = _valid_values("hadoop", %w( 1.0.3 2.2.0 2.4.0 )) master_instance_fleet = _emr_instance_fleet(job[:master]) master_instance_group = _emr_instance_group(job[:master]) placement = job[:placement] || "" service_access_security_group = _ref_string("service_access_security_group", job, "security group") termination = _bool("termination", job, false) _{ AdditionalMasterSecurityGroups add_master_security_groups unless add_master_security_groups.empty? AdditionalSlaveSecurityGroups add_slave_security_groups unless add_slave_security_groups.empty? CoreInstanceFleet core_instance_fleet unless core_instance_fleet.empty? CoreInstanceGroup core_instance_group if core_instance_fleet.empty? Ec2KeyName key_name unless key_name.empty? Ec2SubnetId subnet unless subnet.empty? EmrManagedMasterSecurityGroup emr_master_security_group unless emr_master_security_group.empty? EmrManagedSlaveSecurityGroup emr_slave_security_group unless emr_slave_security_group.empty? HadoopVersion hadoop_version unless hadoop_version.nil? MasterInstanceFleet master_instance_fleet unless master_instance_fleet.empty? MasterInstanceGroup master_instance_group if master_instance_fleet.empty? Placement _{ AvailabilityZone placement } unless placement.empty? ServiceAccessSecurityGroup service_access_security_group unless service_access_security_group.empty? TerminationProtected termination } end
_emr_to_configurations_default_hadoop()
click to toggle source
# File lib/kumogata/template/emr.rb, line 11 def _emr_to_configurations_default_hadoop() [ { classification: "hadoop-env", properties: {}, configurations: [ classification: "export", properties: { JAVA_HOME: "/usr/java/default" }, ], } ] end
_emr_to_configurations_default_hadoop_spark(max_age: 14)
click to toggle source
# File lib/kumogata/template/emr.rb, line 7 def _emr_to_configurations_default_hadoop_spark(max_age: 14) _emr_to_configurations_default_hadoop | _emr_to_configurations_default_spark(max_age: max_age) end
_emr_to_configurations_default_spark(max_age: 14)
click to toggle source
# File lib/kumogata/template/emr.rb, line 24 def _emr_to_configurations_default_spark(max_age: 14) [ { classification: "spark-env", properties: {}, configurations: [ classification: "export", properties: { JAVA_HOME: "/usr/java/default" }, ], }, { classification: "spark-defaults", properties: { "spark.history.fs.cleaner.enabled" => "true", "spark.history.fs.cleaner.interval" => "1d", "spark.history.fs.cleaner.maxAge" => "#{max_age}d", } } ] end
_equals(value1, value2)
click to toggle source
# File lib/kumogata/template/helper.rb, line 205 def _equals(value1, value2) _{ Fn__Equals [ value1, value2 ] } end
_events_pattern(args)
click to toggle source
# File lib/kumogata/template/events.rb, line 15 def _events_pattern(args) # http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEventsandEventPatterns.html#CloudWatchEventsPatterns args[:pattern] || {} end
_events_targets(args)
click to toggle source
# File lib/kumogata/template/events.rb, line 20 def _events_targets(args) ## FIXME ## https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/API_PutTargets.html (args[:targets] || []).collect do |target| role = _ref_attr_string("role", "Arn", target, "role") _{ Arn _ref_attr_string("arn", "Arn", target) Id target[:id] Input target[:input] if target.key? :input InputPath target[:path] if target.key? :path RoleArn role unless role.empty? EcsParameters _{ TaskCount target[:ecs_parameters][:task_count] if target[:ecs_parameters].key? :task_count TaskDefinitionArn _ref_string("task_definition", target[:ecs_parameters], "ecs task definition", "arn") } if target.key? :ecs_parameters } end end
_events_to_schedule_expression(args)
click to toggle source
# File lib/kumogata/template/events.rb, line 6 def _events_to_schedule_expression(args) schedule = args || '5 minutes' if schedule =~ /^(\d+) (minute|minutes|hour|hours|day|days)/ "rate(#{$1} #{$2})" else "cron(#{schedule})" end end
_export(args)
click to toggle source
# File lib/kumogata/template/helper.rb, line 280 def _export(args) export = args[:export] || '' return '' if export.empty? export = "#{export}-#{args[:resource]}" if args.key? :resource _{ Name _sub("${AWS::StackName}-#{export.gsub(/(\s|_)/, '-')}") } end
_export_string(args, prefix)
click to toggle source
# File lib/kumogata/template/helper.rb, line 270 def _export_string(args, prefix) return '' unless args.key? :export return '' unless args[:export] == true export = args[:name] export += "-#{args[:resource]}" if args.key? :resource export += "-#{prefix}" unless prefix.empty? export.gsub(/(\s|_)/, '-') end
_find_in_map(name, top_level, secondary_level)
click to toggle source
# File lib/kumogata/template/helper.rb, line 238 def _find_in_map(name, top_level, secondary_level) _{ Fn__FindInMap [ name, top_level, secondary_level ] } end
_iam_arn(service, resource)
click to toggle source
Amazon Resource Names (ARNs) and AWS Service Namespaces docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
# File lib/kumogata/template/iam.rb, line 208 def _iam_arn(service, resource) def _convert(args) return "" if args.empty? return args if args.is_a? String result = args.collect do |k, v| case k.to_s when "ref" _{ Ref _resource_name(v) } when /ref_(.*)/ _ref_pseudo($1) else v end end (args.size == 1) ? result.first : result end def _value(name, value, default = "*") if value.key? "ref_#{name}".to_sym { ref_: value["ref_#{name}".to_sym] } elsif value.key? "import_#{name}".to_sym { import_: value["import_#{name}".to_sym] } else value[name.to_sym] || default end end arn_prefix = "arn:aws:#{service}" resources = if resource.is_a? String [ { resource: resource } ] elsif resource.is_a? Hash [ resource ] else resource end case service when "apigateway" resources.each_with_index do |v, i| resources[i][:account_id] = false resources[i][:values] = [ _value("path", v) ] end when "execute-api" resources.each_with_index do |v, i| resources[i][:values] = [ _value("id", v), "/", _value("stage", v), "/", _value("http", v), _value("path", v, "/*") ] end when "artifact" resources.each_with_index do |v, i| resources[i][:values] = [ "report-package/", _value("document", v), "/", _value("report", v) ] end when "autoscaling" resources.each_with_index do |v, i| type = case v[:type] when "policy" "scalingPolicy" else "autoScalingGroup" end values = [ type, ":", _value("id", v), ":autoScalingGroupName/", _value("name", v) ] values << _value("sub_name", v) if v[:type] == "policy" resources[i][:values] = values end when "acm" resources.each_with_index do |v, i| resources[i][:values] = [ "certificate/", _value("id", v) ] end when "cloudformation" resources.each_with_index do |v, i| type = if v[:type] == "change" "changeSet" else "stack" end resources[i][:values] = [ type, "/", _value("name", v), "/", _value("id", v) ] end when "cloudsearch" resources.each_with_index{|v, i| resources[i][:values] = [ "domain/", _value("name", v) ] } when "cloudtrail" resources.each_with_index{|v, i| resources[i][:values] = [ "trail/", _value("name", v) ] } when "events" resources.each_with_index do |v, i| resources[i][:region] = "*" resources[i][:account_id] = "*" resources[i][:value] = "*" end when "codebuild" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v, "project"), "/", _value("name", v) ] } when "codecommit" resources.each_with_index{|v, i| resources[i][:values] = [ _value("id", v) ] } when "codedeploy" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v), "/", _value("spec", v) ] } when "cognito-idp" resources.each_with_index{|v, i| resources[i][:values] = [ "userpool/", _value("id", v) ] } when "cognito-identity" resources.each_with_index{|v, i| resources[i][:values] = [ "identitypool/", _value("id", v) ] } when "cognito-sync" resources.each_with_index{|v, i| resources[i][:values] = [ "identitypool/", _value("id", v) ] } when "config" resources.each_with_index{|v, i| resources[i][:values] = [ "config-rule/", _value("name", v) ] } when "codepipeline" resources.each_with_index{|v, i| resources[i][:values] = [ _value("spec", v) ] } when "codestar" resources.each_with_index{|v, i| resources[i][:values] = [ _value("spec", v) ] } when "directconnect" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v), "/", _value("id", v) ] } when "dynamodb" resources.each_with_index{|v, i| resources[i][:values] = [ "table/", _value("name", v) ] } when "ec2" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v), "/", _value("id", v) ] } when "ecr" resources.each_with_index{|v, i| resources[i][:values] = [ "repository/", _value("name", v) ] } when "ecs" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v), "/", _value("name", v) ] } when "elasticbeanstalk" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v), "/", _value("name", v) ] } when "elasticache" resources.each_with_index do |v, i| type = v[:type] || "cluster" resources[i][:values] = [ type, ":", _value("name", v) ] end when "elasticfilesystem" resources.each_with_index{|v, i| resources[i][:values] = [ "file-system/", _value("id", v) ] } when "elasticloadbalancing" resources.each_with_index do |v, i| v[:type] = "loadbalancer" unless v.key? :type type = if v.key? :elb v[:type] else if v[:type] == "targetgroup" v[:type] else "#{v[:type]}/app" end end values = [ type, "/", _value("name", v) ] values << [ "/", _value("id", v) ] unless v.key? :elb resources[i][:values] = values end when "elastictranscoder" resources.each_with_index{|v, i| resources[i][:values] = [ _value("resource", v), "/", _value("id", v) ] } when "es" resources.each_with_index{|v, i| resources[i][:values] = [ "domain/", _value("name", v) ] } when "firehose" resources.each_with_index{|v, i| resources[i][:values] = [ "deliverystream/", _value("name", v) ] } when "glacier" resources.each_with_index{|v, i| resources[i][:values] = [ "valuts/", _value("name", v) ] } when "health" resources.each_with_index do |v, i| type = v[:type] || "event" resources[i][:account_id] = false if type == "event" resources[i][:values] = [ type, "/", _value("id", v) ] end when "iam" resources.each_with_index do |v, i| resources[i][:region] = false v[:name] = if v.key? :type and v[:type] == "policy" _iam_to_policy(v[:name]) else v[:name] end if v.key? :type resources[i][:values] = [ _value("type", v), "/", _value("name", v) ] else resources[i][:value] = "root" end end when "iot" resources.each_with_index do |v, i| type = v[:type] value_key = if type == "cert" "id" else "name" end resources[i][:values] = [ v[:type], "/", _value(value_key, v) ] end when "kinesis" resources.each_with_index{|v, i| resources[i][:values] = [ "stream/", _value("name", v) ] } when "kms" resources.each_with_index do |v, i| type = v[:type] || "key" value_key = if type == "key" "id" else "alias" end resources[i][:values] = [ v[:type] || "key", "/", _value(value_key, v) ] end when "lambda" resources.each_with_index do |v, i| type = v[:type] || "function" values = [ type, ":", _value("name", v) ] values << [ ":", _value("alias", v) ] if v.key? :alias values << [ ":", _value("id", v) ] if v.key? :id resources[i][:values] = values end when "logs" resources.each_with_index do |v, i| resources[i][:region] = v[:region] if v.key? :region resources[i][:values] = [ _value("type", v), ':', _value("name", v) ] resources[i][:values] += [ ':', 'log-stream', ':', _value("stream", v) ] if v.key? :stream end when "machinelearning" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v), "/", _value("id", v) ] } when "mobilehub" resources.each_with_index{|v, i| resources[i][:values] = [ "project/", _value("id", v) ] } when "mobiletargeting" resources.each_with_index do |v, i| resources[i][:region] = AWS_REGION[:virginia] resources[i][:values] = (v.key? :reports) ? [ 'reports' ] : [ 'apps', '/', _value("app", v) ] resources[i][:values] += [ '/', 'campaigns', '/', _value("campaigns", v) ] if v.key? :campaigns resources[i][:values] += [ '/', 'segments', '/', _value("segments", v) ] if v.key? :segments end when "organizations" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v), "/", _value("id", v) ] } when "polly" resources.each_with_index{|v, i| resources[i][:values] = [ "lexicon/", _value("name", v) ] } when "redshift", "rds" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v), "/", _value("name", v) ] } when "route53" resources.each_with_index do |v, i| resources[i][:account_id] = false resources[i][:region] = false resources[i][:values] = [ _value("type", v), "/", _value("id", v) ] end when "s3" arn_prefix_s3 = "#{arn_prefix}:::" if resource.is_a? String return "#{arn_prefix_s3}#{resource}" elsif resource.is_a? Hash return _join([ arn_prefix_s3, _convert(resource) ], "") else s3, s3_map = [], [] resources.each_with_index do |v, i| if v.is_a? String s3 << v elsif v.is_a? Hash s3 << _convert(v) else tmp = [ arn_prefix_s3 ] tmp += v.collect{|vv| _convert(vv) } s3_map << _{ Fn__Join "", tmp } end end return s3_map unless s3_map.empty? if s3.select{|v| v.is_a? Hash }.empty? return s3.collect{|v| "#{arn_prefix_s3}#{v}" } else return _join(s3.insert(0, arn_prefix_s3), "") end end when "ses" resources.each_with_index{|v| resources[i][:value] = v } when "sns" resources.each_with_index do |v, i| values = [ _value("name", v) ] values << [ ":", _value("id", v) ] if v.key? :id resources[i][:values] = values end when "ssm" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v), "/", _value("id", v) ] } when "sqs" resources.each_with_index{|v, i| resources[i][:values] = [ _value("name", v) ] } when "states" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v), ":", _value("name", v) ] } when "storagegateway" resources.each_with_index{|v, i| resources[i][:values] = [ _value("type", v), "/", _value("name", v) ] } when "sts" resources.each_with_index do |v, i| resources[i][:region] = false resources[i][:value] = if v.key? :type "#{v[:type]}/#{v[:name]}" else "root" end end when "trustedadvisor" resources.each_with_index do |v, i| resources[i][:region] = false resources[i][:values] = [ "checks/", _value("code", v), "/", _value("id", v) ] end when "waf" resources.each_with_index do |v, i| resources[i][:region] = false resources[i][:values] = [ _value("type", v), "/", _value("id", v) ] end end _iam_arn_resource(arn_prefix, resources) end
_iam_arn_resource(prefix, resource)
click to toggle source
# File lib/kumogata/template/iam.rb, line 565 def _iam_arn_resource(prefix, resource) def _arn(arn, value) "#{arn}#{value}".include?("${") ? _sub("#{arn}#{value}") : "#{arn}#{value}" end resources = if resource.is_a? String or resource.is_a? Hash [ resource ] else resource end result = resources.collect do |v| region = if v.is_a? Hash and v.key? :region v[:region] else _var_pseudo("region") end account = if v.is_a? Hash and v.key? :account_id v[:account_id] else _var_pseudo("account_id") end arn = if account == false "#{prefix}:#{region}::" elsif region == false "#{prefix}::#{account}:" else "#{prefix}:#{region}:#{account}:" end if v.is_a? String _arn(arn, v) else if v.key? :value _arn(arn, v[:value]) else values = v[:values] || [] if values.empty? _arn(arn, "*:*") else if values.select{|vv| vv.is_a? Hash }.empty? _arn(arn, values.join("")) else values.collect!{|vv| (vv.is_a? String) ? vv : _ref_string("", vv) } _join([ _arn(arn, ""), values ].flatten, "") end end end end end (result.length == 1) ? result.first : result end
_iam_assume_role_policy_document(args)
click to toggle source
# File lib/kumogata/template/iam.rb, line 151 def _iam_assume_role_policy_document(args) cognito = args[:cognito] || false aws = args[:aws] || [] federated = if cognito "cognito-identity.#{DOMAIN}" else args[:federated] || "" end service = if args.key? :services or args.key? :service (args[:services] || [ args[:service] ]).collect{|v| "#{v}.#{DOMAIN}" } else '' end canonical = args[:canonical] || "" action = if cognito "assume role with web identity" else args[:action] || "assume role" end cond_auds = _ref_string_default("cond_auds", args) cond_external = _ref_string_default("cond_external", args) cond_amr = args[:cond_amr] || "" condition = unless cond_auds.empty? and cond_external.empty? and cond_amr.empty? true else false end [ _{ Effect "Allow" Principal _{ AWS _iam_arn("iam", aws) unless aws.empty? Federated federated unless federated.empty? Service service unless service.empty? CanonicalUser canonical unless canonical.empty? } Action [ "sts:#{_capitalize(action)}" ] Condition _{ StringEquals _{ cognito____identity___amazonaws___com_aud cond_auds unless cond_auds.empty? sts_ExternalId cond_external unless cond_external.empty? } ForAnyValue_StringLike _{ cognito____identity___amazonaws___com_amr cond_amr unless cond_amr.empty? } if cognito } if condition } ] end
_iam_login_profile(args)
click to toggle source
# File lib/kumogata/template/iam.rb, line 621 def _iam_login_profile(args) password = args[:password] || "" reset_required = _bool("reset_required", args, true) _{ Password password PasswordResetRequired reset_required } end
_iam_managed_policies(args)
click to toggle source
# File lib/kumogata/template/iam.rb, line 631 def _iam_managed_policies(args) (args[:managed_policies] || []).collect do |v| _iam_arn("iam", { account_id: "aws", type: "policy", name: v }) end end
_iam_policies(name, args)
click to toggle source
# File lib/kumogata/template/iam.rb, line 26 def _iam_policies(name, args) (args[name.to_sym] || []).collect.with_index do |v, i| case v[:policy] when 'pinpoint-full' v[:document] = _pinpoint_to_iam_full(v[:app]) end v[:name] = "policy-#{i + 1}" _{ PolicyDocument do Version "2012-10-17" Statement _iam_policy_document("document", v) end PolicyName _name("policy", v) } end end
_iam_policy_conditions(args)
click to toggle source
# File lib/kumogata/template/iam.rb, line 637 def _iam_policy_conditions(args) args = [ args ] if args.is_a? Hash conditions = {} args.each do |v| case v when 's3 bucket owner full control' v = _iam_to_condition_s3_bucket_owner_full_control end if v.is_a? String v.each_pair do |kk, vv| operator = case kk.to_s when '=' 'Equals' when '!=' 'NotEquals' when '==' 'EqualsIgnoreCase' when '!==' 'NotEqualsIgnoreCase' when '=~' 'Like' when '!~' 'NotLike' when '<' 'LessThan' when '<=' 'LessThanEquals' when '>' 'GreaterThan' when '>=' 'GreaterThanEquals' end type = if vv.key? :type case vv[:type] when /str/ 'String' when /int/ 'Numeric' when /date/ 'Date' when /bool/ 'Bool' when /bin/ 'Binary' when /ip/ 'IpAddress' when /noip/ 'NotIpAddress' when /arn/ 'Arn' when /null/, /nil/ 'Null' else 'String' end else 'String' end vv.delete(:type) if vv.key? :type operator = '' if type =~ /(Ip|Null)/ if vv.key? :exists exists = 'IfExists' vv.delete(:exists) end value = {} vv.each_pair do |kkk, vvv| if vvv.is_a? Integer type = 'Numeric' vvv = vvv.to_s elsif vvv.is_a? TrueClass or vvv.is_a? FalseClass type = 'Bool' operator = '' vvv = vvv.to_s end value[kkk.to_s] = vvv end conditions["#{type}#{operator}#{exists}"] = value end end conditions end
_iam_policy_document(name, args)
click to toggle source
# File lib/kumogata/template/iam.rb, line 96 def _iam_policy_document(name, args) (args[name.to_sym] || []).collect do |v| _services = if v.key? :service [ v[:service] ] else v[:services] || [] end next if _services.empty? _actions = if v.key? :action [ v[:action] ] else v[:actions] || [ "*" ] end sid = v[:sid] || '' actions = [] _services.each do |s| _actions.each do |a| actions << unless a[0].match(/^[a-z]/).nil? "#{s}:#{_capitalize(a)}" else "#{s}:#{a}" end end end resource = if v.key? :resources _services.collect{|s| _iam_arn(s, v[:resources]) }.flatten elsif v.key? :resource _services.collect{|s| _iam_arn(s, v[:resource]) }.flatten else [ "*" ] end principal = _iam_policy_principal(v) not_principal = _iam_policy_principal(v, "not_principal") _{ Sid sid unless sid.empty? Effect v[:effect] || 'Allow' NotAction v[:no_action] if v.key? :no_action Action actions Resource resource unless v.key? :no_resource Principal principal unless principal.empty? NotPrincipal not_principal unless not_principal.empty? Condition _iam_policy_conditions(v[:condition]) if v.key? :condition } end end
_iam_policy_principal(args, key = "principal")
click to toggle source
# File lib/kumogata/template/iam.rb, line 44 def _iam_policy_principal(args, key = "principal") principal = args[key.to_sym] || {} return "" if principal.empty? return principal if principal.is_a? String if principal.key? :account account = principal[:account] if account.is_a? Hash _{ AWS _iam_arn("iam", { type: "user", account_id: account[:id], name: account[:name] }) } else _{ AWS account } end elsif principal.key? :accounts accounts = principal[:accounts].collect do |v| _iam_arn("iam", { type: "user", account_id: v[:id], name: v[:name] }) end _{ AWS accounts } elsif principal.key? :federated _{ Federated principal[:federated] } elsif principal.key? :assumed_role assumed_role = principal[:assumed_role] _{ AWS _iam_arn("sts", { type: "assumed-role", account_id: assumed_role[:id], name: assumed_role[:name] }) } elsif principal.key? :service_region _{ Service _sub_service(principal[:service_region]) } elsif principal.key? :services or principal.key? :service _{ Service principal[:services] || principal[:service] } elsif principal.key? :canonical _{ CanonicalUser principal[:canonical] } else '' end end
_iam_to_condition_s3_bucket_owner_full_control()
click to toggle source
# File lib/kumogata/template/iam.rb, line 22 def _iam_to_condition_s3_bucket_owner_full_control() { '=': { 's3:x-amz-acl': 'bucket-owner-full-control' } } end
_iam_to_policy(value)
click to toggle source
# File lib/kumogata/template/iam.rb, line 7 def _iam_to_policy(value) case value when 'admin' 'AdministratorAccess' when 'power' 'PowerUserAccess' when /readonly/ 'ReadOnlyAccess' when 'database', 'network', 'system' "#{value.upcase}Administrator" else value end end
_if(name, value_if_true, value_if_false)
click to toggle source
# File lib/kumogata/template/helper.rb, line 209 def _if(name, value_if_true, value_if_false) _{ Fn__If [ name, value_if_true, value_if_false ] } end
_import(name, ref_name = '', append_import_name = '')
click to toggle source
# File lib/kumogata/template/helper.rb, line 316 def _import(name, ref_name = '', append_import_name = '') import = name import += "-#{ref_name}" unless ref_name.empty? import += "-#{append_import_name}" unless append_import_name.empty? _{ Fn__ImportValue _sub(import.gsub(/(\s|_)/, '-')) } end
_integer(name, args, default = 0)
click to toggle source
# File lib/kumogata/template/helper.rb, line 22 def _integer(name, args, default = 0) args.key?(name.to_sym) ? args[name.to_sym].to_i : default end
_join(args, delimiter = ",")
click to toggle source
# File lib/kumogata/template/helper.rb, line 312 def _join(args, delimiter = ",") _{ Fn__Join delimiter, args } end
_kinesis_firehose_delivery_stream_buffering_hints(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 116 def _kinesis_firehose_delivery_stream_buffering_hints(args) args = { interval: 300, size: 5 } if args.nil? _{ IntervalInSeconds args[:interval] SizeInMBs args[:size] } end
_kinesis_firehose_delivery_stream_cloudwatch_logging(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 125 def _kinesis_firehose_delivery_stream_cloudwatch_logging(args) # FIXME change name by delivery name args = { enabled: true, group: '/aws/kinesisfirehorse', stream: 'S3Delivery' } if args.nil? enabled = _bool('enabled', args, true) group = args[:group] stream = args[:stream] _{ Enabled enabled LogGroupName group LogStreamName stream } end
_kinesis_firehose_delivery_stream_elasticsearch_destination(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 84 def _kinesis_firehose_delivery_stream_elasticsearch_destination(args) return {} if args.nil? buffering = _kinesis_firehose_delivery_stream_buffering_hints(args[:buffering_hints]) cloudwatch = _kinesis_firehose_delivery_stream_cloudwatch_logging(args[:logging]) domain = _ref_attr_string('domain', 'DomainArn', args, 'elasticsearch domain') index_name = args[:index] index_rotation = _valid_values(args[:index_rotation], %w( NoRotation OneHour OneDay OneWeek OneMonth ), 'NoRotation') processing = _kinesis_firehose_delivery_stream_processing(args[:processing]) retry_options = _kinesis_firehose_delivery_stream_elasticsearch_retry(args[:retry]) role = _ref_attr_string('role', 'Arn', args, 'role') s3_backup = _kinesis_firehose_to_elasticsearch_destination(args[:s3_backup]) s3_dest = _kinesis_firehose_delivery_stream_s3_destnation(args[:s3_dest]) type = args[:type] _{ BufferingHints buffering CloudWatchLoggingOptions cloudwatch unless cloudwatch.empty? DomainARN domain IndexName index_name IndexRotationPeriod index_rotation ProcessingConfiguration processing unless processing.empty? RetryOptions retry_options RoleARN role S3BackupMode s3_backup S3Configuration s3_dest Type type } end
_kinesis_firehose_delivery_stream_encryption(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 201 def _kinesis_firehose_delivery_stream_encryption(args) return _{ NoEncryptionConfig 'NoEncryption' } if args.nil? kms = _kinesis_firehose_delivery_stream_kms_encryption(args[:kms]) _{ KMSEncryptionConfig kms unless kms.empty? NoEncryptionConfig 'NoEncryption' if kms.empty? } end
_kinesis_firehose_delivery_stream_extended_s3_destination(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 234 def _kinesis_firehose_delivery_stream_extended_s3_destination(args) return {} if args.nil? bucket = _ref_attr_string('bucket', 'Arn', args, 'bucket') buffering = _kinesis_firehose_delivery_stream_buffering_hints(args[:buffering_hints]) cloudwatch = _kinesis_firehose_delivery_stream_cloudwatch_logging(args[:logging]) compression = _kinesis_firehose_to_s3_destinaiton_compression(args[:compression]) encryption = _kinesis_firehose_delivery_stream_encryption(args[:encryption]) prefix = args[:prefix] || '' role = _ref_attr_string('role', 'Arn', args, 'role') s3_backup = _kinesis_firehose_delivery_stream_s3_destnation(args[:s3_backup]) s3_backup_mode = _kinesis_firehose_to_elasticsearch_destination(args[:s3_backup_mode]) _{ BucketARN bucket BufferingHints buffering CloudWatchLoggingOptions cloudwatch unless cloudwatch.empty? CompressionFormat compression EncryptionConfiguration encryption unless encryption.empty? Prefix prefix ProcessingConfiguration processing unless processing.empty? RoleARN role S3BackupConfiguration s3_backup unless s3_backup.empty? S3BackupMode s3_backup_mode } end
_kinesis_firehose_delivery_stream_kinesis_stream_source(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 222 def _kinesis_firehose_delivery_stream_kinesis_stream_source(args) return {} if args.nil? kinesis = _ref_attr_string('stream', 'Arn', args, 'kinesis stream') role = _ref_attr_string('role', 'Arn', args, 'role') _{ KinesisStreamARN kinesis RoleARN role } end
_kinesis_firehose_delivery_stream_kms_encryption(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 212 def _kinesis_firehose_delivery_stream_kms_encryption(args) return {} if args.nil? kms = _ref_attr_string('kms', 'Arn', args, 'kms key') _{ AWSKMSKeyARN kms } end
_kinesis_firehose_delivery_stream_processing(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 140 def _kinesis_firehose_delivery_stream_processing(args) return {} if args.nil? enabled = _bool('enabled', args, true) processors = _kinesis_firehose_delivery_stream_processor(args[:processor]) _{ Enabled enabled Processors processors } end
_kinesis_firehose_delivery_stream_processor(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 152 def _kinesis_firehose_delivery_stream_processor(args) parameters = _kinesis_firehose_delivery_stream_processor_parameters(args[:parameters]) _{ Parameters parameters Type 'Lambda' } end
_kinesis_firehose_delivery_stream_processor_parameters(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 161 def _kinesis_firehose_delivery_stream_processor_parameters(args) args.collect do |k, v| _{ ParameterName k ParameterValue v } end end
_kinesis_firehose_delivery_stream_redshift_destination(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 261 def _kinesis_firehose_delivery_stream_redshift_destination(args) return {} if args.nil? cloudwatch = _kinesis_firehose_delivery_stream_cloudwatch_logging(args[:logging]) cluster = _ref_string('cluster', args, 'redshift cluster jdbc url') password = _ref_string('password', args, 'redshift cluster master user password') processing = _kinesis_firehose_delivery_stream_processing(args[:processing]) role = _ref_attr_string('role', 'Arn', args, 'role') s3 = _kinesis_firehose_delivery_stream_s3_destnation(args[:s3]) user = _ref_string('user', args, 'redshift cluster master user name') _{ CloudWatchLoggingOptions cloudwatch unless cloudwatch.empty? ClusterJDBCURL cluster CopyCommand copy Password password ProcessingConfiguration processing unless processing.empty? RoleARN role S3Configuration s3 Username user } end
_kinesis_firehose_delivery_stream_retry(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 170 def _kinesis_firehose_delivery_stream_retry(args) duration = args[:duration] || 300 _{ DurationInSeconds duration } end
_kinesis_firehose_delivery_stream_s3_destnation(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 178 def _kinesis_firehose_delivery_stream_s3_destnation(args) return {} if args.nil? bucket = _ref_attr_string('bucket', 'Arn', args, 'bucket') buffering = _kinesis_firehose_delivery_stream_buffering_hints(args[:buffering_hints]) cloudwatch = _kinesis_firehose_delivery_stream_cloudwatch_logging(args[:logging]) compression = _kinesis_firehose_to_s3_destinaiton_compression(args[:compression]) encryption = _kinesis_firehose_delivery_stream_encryption(args[:encryption]) prefix = args[:prefix] || '' prefix = "#{prefix}/" if prefix !~ /^.*[-|\/]$/ role = _ref_attr_string('role', 'Arn', args, 'role') _{ BucketARN bucket BufferingHints buffering CloudWatchLoggingOptions cloudwatch CompressionFormat compression EncryptionConfiguration encryption Prefix prefix unless prefix.empty? RoleARN role } end
_kinesis_firehose_to_delivery_stream_role(args)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 7 def _kinesis_firehose_to_delivery_stream_role(args) role = [] # TODO add more destination: redshift and elasticsearch service KINESIS_FIREHOSE_DELIVERY_STREAM_ROLE.each do |v| next if v[:service] == 'lambda' and !args.key? :lambda next if v[:service] == 'kms' and !args.key? :key _role = { service: v[:service], actions: v[:actions] } _role[:resources] = v[:resources].collect do |vv| if vv.is_a? String if args.key? :bucket vv.gsub('%BUCKET_NAME%', args[:bucket]) elsif args.key? :key vv.gsub('%KEY%', args[:key]) end elsif vv.is_a? Hash vv.each_pair do |kkk, vvv| vv[kkk] = vvv. gsub('%STREAM_NAME%', args[:name]). gsub('%LOG_GROUP_NAME%', args[:name]). gsub('%LOG_STREAM_NAME%', '*') end end end _role[:condition] = v[:condition].collect do |vv| vv.each_pair do |kkk, vvv| # FIXME s3 or ... case vvv.first[0] when /kms:ViaService/ vv[kkk][vvv.first[0]] = _sub_service('s3') when /aws:s3:arn/ vv[kkk][vvv.first[0]] = _iam_arn('s3', "#{args[:bucket]}/*") end end end if v.key? :condition role << _role end role end
_kinesis_firehose_to_delivery_stream_type(value)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 47 def _kinesis_firehose_to_delivery_stream_type(value) case value when /direct/ 'DirectPut' when /kinesis/ 'KinesisStreamAsSource' else 'DirectPut' end end
_kinesis_firehose_to_elasticsearch_destination(value)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 58 def _kinesis_firehose_to_elasticsearch_destination(value) case value when /failed/ 'FailedDocumentsOnly' when /all/ 'AllDocuments' else 'FailedDocumentsOnly' end end
_kinesis_firehose_to_s3_destinaiton_compression(value)
click to toggle source
# File lib/kumogata/template/kinesis.rb, line 69 def _kinesis_firehose_to_s3_destinaiton_compression(value) case value when /un/ 'UNCOMPRESSED' when 'gzip' 'GZIP' when 'zip' 'ZIP' when 'snappy' 'Snappy' else 'UNCOMPRESSED' end end
_lambda_dead_letter(args)
click to toggle source
# File lib/kumogata/template/lambda.rb, line 74 def _lambda_dead_letter(args) return "" unless args.key? :dead_latter dead_letter = _ref_string("dead_letter", args) _{ TargetArn dead_letter } end
_lambda_function_code(args)
click to toggle source
# File lib/kumogata/template/lambda.rb, line 29 def _lambda_function_code(args) return "" unless args.key? :code code = args[:code] is_s3 = (code.key? :zip_file) ? false : true s3_bucket = code[:s3_bucket] || "" s3_key = code[:s3_key] || "" s3_object_version = code[:s3_object_version] || "" zip_file = code[:zip_file] || "" unless zip_file.empty? zip_file_code = [] File.foreach(zip_file) do |file| file.each_line.collect{|line| zip_file_code << line.chomp } end end _{ S3Bucket s3_bucket if is_s3 S3Key s3_key if is_s3 S3ObjectVersion s3_object_version if is_s3 and !s3_object_version.empty? ZipFile _join(zip_file_code, "\n") unless is_s3 } end
_lambda_function_environment(args)
click to toggle source
# File lib/kumogata/template/lambda.rb, line 53 def _lambda_function_environment(args) environment = args[:environment] || {} return {} if environment.empty? _{ Variables environment } end
_lambda_to_runtime(value)
click to toggle source
# File lib/kumogata/template/lambda.rb, line 6 def _lambda_to_runtime(value) case value when 'node4' 'nodejs4.3' when 'node6' 'nodejs6.10' when 'node8' 'nodejs8.10' when 'python2' 'python2.7' when 'python3' 'python3.6' when '.net1' 'dotnetcore1.0' when '.net2' 'dotnetcore2.0' when 'go' 'go1.x' else value end end
_lambda_trace_config(args)
click to toggle source
# File lib/kumogata/template/lambda.rb, line 83 def _lambda_trace_config(args) trace = args[:trace] || "" return trace if trace.empty? mode = case trace when "active" "Active" else "PassThrough" end _{ Mode mode } end
_lambda_vpc_config(args)
click to toggle source
# File lib/kumogata/template/lambda.rb, line 60 def _lambda_vpc_config(args) return "" unless args.key? :vpc vpc = args[:vpc] security_group_ids = _ref_array("security_groups", vpc, "security group") subnet_ids = _ref_array("subnets", vpc, "subnet") return {} if security_group_ids.empty? and subnet_ids.empty? _{ SecurityGroupIds security_group_ids unless security_group_ids.empty? SubnetIds subnet_ids unless subnet_ids.empty? } end
_logs_metric_filter_transformations(args)
click to toggle source
# File lib/kumogata/template/logs.rb, line 6 def _logs_metric_filter_transformations(args) (args[:transformations] || []).collect do |tran| _{ MetricName tran[:name] MetricNamespace tran[:ns] MetricValue tran[:value] } end end
_maintenance_window(service, start_time)
click to toggle source
# File lib/kumogata/template/helper.rb, line 422 def _maintenance_window(service, start_time) start_time = start_time.utc format = "%a:%H:%M" case service when "elasticache" # 60 min end_time = start_time + (60 * 60) when "rds" # 30 min end_time = start_time + (60 * 30) when "redshift" # 30 min end_time = start_time + (60 * 30) end "#{start_time.strftime(format)}-#{end_time.strftime(format)}" end
_name(name, args, prefix = "-")
click to toggle source
# File lib/kumogata/template/helper.rb, line 69 def _name(name, args, prefix = "-") return _import(args["import_#{name}".to_sym]) if args.key? "import_#{name}".to_sym ref_name = _ref_string(name, args) if ref_name.empty? ref_name_default = _ref_string("name", args) _join([ _ref(_resource_name("service")), (ref_name_default.is_a? String) ? ref_name_default.gsub(' ', prefix) : ref_name_default, ], prefix) else (ref_name.is_a? String) ? ref_name.gsub(' ', prefix) : ref_name end end
_nlb_to_lb_cross_zone(value = true)
click to toggle source
# File lib/kumogata/template/nlb.rb, line 6 def _nlb_to_lb_cross_zone(value = true) { "load_balancing.cross_zone.enabled": value } end
_not(conditions)
click to toggle source
# File lib/kumogata/template/helper.rb, line 213 def _not(conditions) _{ Fn__Not conditions } end
_or(conditions)
click to toggle source
# File lib/kumogata/template/helper.rb, line 217 def _or(conditions) _{ Fn__Or conditions } end
_pair_name_value(args, name)
click to toggle source
# File lib/kumogata/template/helper.rb, line 36 def _pair_name_value(args, name) _pair_value(args, name, "name") end
_pair_value(args, name, key_prefix = "key")
click to toggle source
# File lib/kumogata/template/helper.rb, line 40 def _pair_value(args, name, key_prefix = "key") return "" unless args.key? name.to_sym pair = args[name.to_sym] if pair.is_a? Hash pair.map.collect do |key, value| case value when /^_ref_(.*)$/ value = _ref_pseudo($1) when /^_import_(.*)$/ value = _import($1) end p = { "#{key_prefix.capitalize}": key.to_s } p['Value'] = value p end else pair.collect do |p| p.map.collect do |_, value| _{ Value value } end end end end
_pinpoint_to_iam_full(app)
click to toggle source
# File lib/kumogata/template/pinpoint.rb, line 31 def _pinpoint_to_iam_full(app) [ { service: 'mobiletargeting', actions: [ 'delete *', 'get *', 'update *', ], resource: [ { app: app }, { app: "#{app}/*" }, ], }, { service: 'mobiletargeting', actions: [ 'get reports', ], resource: [ { reports: true }, ], }, ] end
_pinpoint_to_iam_readonly(app)
click to toggle source
# File lib/kumogata/template/pinpoint.rb, line 7 def _pinpoint_to_iam_readonly(app) [ { service: 'mobiletargeting', actions: [ 'get *', ], resource: [ { app: app }, { app: "#{app}/*" }, ], }, { service: 'mobiletargeting', actions: [ 'get reports', ], resource: [ { reports: true }, ], }, ] end
_pinpoint_to_kinesis_firehose_delivery_stream_role(args)
click to toggle source
# File lib/kumogata/template/pinpoint.rb, line 71 def _pinpoint_to_kinesis_firehose_delivery_stream_role(args) role = [] PINPOINT_KINESIS_FIREHOSE_DELIVERY_STREAM_ROLE.each do |v| _role = { service: v[:service], actions: v[:actions] } _role[:resources] = v[:resources].collect do |vv| vv.each_pair do |kkk, vvv| vv[kkk] = vvv.gsub(/%FIREHOSE_DELIVERY_STREAM_NAME%/, args[:name]) end end role << _role end role end
_pinpoint_to_kinesis_stream_role(args)
click to toggle source
# File lib/kumogata/template/pinpoint.rb, line 57 def _pinpoint_to_kinesis_stream_role(args) role = [] PINPOINT_KINESIS_STREAM_ROLE.each do |v| _role = { service: v[:service], actions: v[:actions] } _role[:resources] = v[:resources].collect do |vv| vv.each_pair do |kkk, vvv| vv[kkk] = vvv.gsub(/%KINESIS_STREAM_NAME%/, args[:name]) end end role << _role end role end
_pseudo(type)
click to toggle source
# File lib/kumogata/template/helper.rb, line 170 def _pseudo(type) case type when "account id", "account_id" "AccountId" when "notification arns", "notification_arns" "NotificationARNs" when "no value", "no_value" "NoValue" when "region" "Region" when "stack id", "stack_id" "StackId" when "stack name", "stack_name" "StackName" else type end end
_rds_option_group_configurations(args)
click to toggle source
# File lib/kumogata/template/rds.rb, line 34 def _rds_option_group_configurations(args) (args[:configurations] || []).collect do |v| security_groups = v[:security_groups] || [] settings = v[:settings] || {} port = v[:port] || "" vpc_security_groups = v[:security_groups] || [] _{ DBSecurityGroupMemberships security_groups unless security_groups.empty? OptionName v[:name] OptionSettings _{ Name settings[:name] Value settings[:value] } unless settings.empty? Port port unless port.empty? VpcSecurityGroupMemberships vpc_security_groups unless vpc_security_groups.empty? } end end
_rds_to_event_subscription_source(value)
click to toggle source
# File lib/kumogata/template/rds.rb, line 17 def _rds_to_event_subscription_source(value) case value when "instance" "db-instance" when "parameter", "parameter group" "db-parameter-group" when "security", "security group" "db-security-group" when "snapshot" "db-snapshot" when /db-/ value else "db-instance" end end
_rds_to_parameter_charset(charset = 'utf8mb4')
click to toggle source
# File lib/kumogata/template/rds.rb, line 6 def _rds_to_parameter_charset(charset = 'utf8mb4') { "character-set-client-handshake": 1, "character_set_client": charset, "character_set_connection": charset, "character_set_database": charset, "character_set_results": charset, "character_set_server": charset, } end
_redshift_logging(args)
click to toggle source
# File lib/kumogata/template/redshift.rb, line 24 def _redshift_logging(args) logging = args[:logging] || "" return logging if logging.empty? bucket = _ref_string("bucket", logging, "bucket") key = _ref_string("key", logging, "key") _{ BucketName bucket S3KeyPrefix key } end
_redshift_parameters(args)
click to toggle source
# File lib/kumogata/template/redshift.rb, line 6 def _redshift_parameters(args) (args[:parameters] || []).collect do |v| name = v[:name] || "" value = if name == "wlm_json_configuration" v[:value].to_json else v[:value] || "" end next if name.empty? or value.empty? _{ ParameterName name ParameterValue value } end end
_ref(name)
click to toggle source
# File lib/kumogata/template/helper.rb, line 189 def _ref(name) _{ Ref name } end
_ref_arn(service, name)
click to toggle source
# File lib/kumogata/template/helper.rb, line 158 def _ref_arn(service, name) _join([ "arn:aws:#{service}:::", _ref(_resource_name(name)) ], ",") end
_ref_array(name, args, ref_name = '', attr_name = '', append_import_name = '')
click to toggle source
# File lib/kumogata/template/helper.rb, line 121 def _ref_array(name, args, ref_name = '', attr_name = '', append_import_name = '') if args["import_#{name}".to_sym].is_a? String [ _import(name, ref_name, append_import_name) ] elsif args["ref_#{name}".to_sym].is_a? String if attr_name.empty? [ _ref_string(name, args, ref_name) ] else [ _attr_string(name, attr_name, ref_name) ] end else array = [] array += args["import_#{name}".to_sym].collect do |v| _import(v, ref_name, append_import_name) end if args.key? "import_#{name}".to_sym array += args["ref_#{name}".to_sym].collect do |v| if attr_name.empty? _ref(_resource_name(v, ref_name)) else _attr_string(v, attr_name, ref_name) end end if args.key? "ref_#{name}".to_sym array.empty? ? _array(args[name.to_sym] || []) : array end end
_ref_attr_string(name, attr, args, ref_name = '', append_import_name = '')
click to toggle source
# File lib/kumogata/template/helper.rb, line 146 def _ref_attr_string(name, attr, args, ref_name = '', append_import_name = '') if args.key? "import_#{name}".to_sym _import(args["import_#{name}".to_sym], ref_name, append_import_name) elsif args.key? "ref_#{name}".to_sym _attr_string(args["ref_#{name}".to_sym], attr, ref_name) elsif args.key? name.to_sym args[name.to_sym] else '' end end
_ref_key?(name, args, ref_name = '', check_name = true)
click to toggle source
# File lib/kumogata/template/helper.rb, line 102 def _ref_key?(name, args, ref_name = '', check_name = true) return true if args.key? "import_#{name}".to_sym return true if args.key? "ref_#{name}".to_sym return true if check_name and args.key? name.to_sym false end
_ref_pseudo(type)
click to toggle source
# File lib/kumogata/template/helper.rb, line 162 def _ref_pseudo(type) _ref("AWS::#{_pseudo(type)}") end
_ref_string(name, args, ref_name = '', append_import_name = '')
click to toggle source
# File lib/kumogata/template/helper.rb, line 109 def _ref_string(name, args, ref_name = '', append_import_name = '') return _import(args["import_#{name}".to_sym], ref_name, append_import_name) if args.key? "import_#{name}".to_sym return args[name.to_sym].to_s || '' unless args.key? "ref_#{name}".to_sym _ref(_resource_name(args["ref_#{name}".to_sym].to_s, ref_name)) end
_ref_string_default(name, args, ref_name = '', default = '')
click to toggle source
# File lib/kumogata/template/helper.rb, line 116 def _ref_string_default(name, args, ref_name = '', default = '') ref_string = _ref_string(name, args, ref_name) ref_string.empty? ? default : ref_string end
_region()
click to toggle source
# File lib/kumogata/template/helper.rb, line 323 def _region _ref_pseudo("region") end
_resource_name(name, append = nil)
click to toggle source
# File lib/kumogata/template/helper.rb, line 84 def _resource_name(name, append = nil) resource = name.to_s.clone resource += " #{append}" unless append.nil? resource.gsub(/[^0-9A-Za-z]/, ' ').split(' ').map(&:capitalize).join() end
_s3_cors(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 92 def _s3_cors(args) rules = (args[:cors] || []).collect do |rule| _{ AllowedHeaders _array(rule[:headers]) if rule.key? :headers AllowedMethods _array(rule[:methods]) AllowedOrigins _array(rule[:origins]) ExposedHeaders _array(rule[:exposed_headers]) if rule.key? :exposed_headers Id rule[:id] if rule.key? :id MaxAge rule[:max_age] if rule.key? :max_age } end return rules if rules.empty? _{ CorsRules rules } end
_s3_lifecycle(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 110 def _s3_lifecycle(args) rules = (args[:lifecycles] || []).collect do |rule| noncurrent_transitions = _s3_lifecycle_noncurrent_version_transition(rule) status = if rule.key? :status _bool('status', rule, true) ? "Enabled" : "Disabled" else "Enabled" end transitions = _s3_lifecycle_transition(rule) _{ ExpirationDate _timestamp_utc(rule[:exp_date]) if rule.key? :exp_date ExpirationInDays rule[:exp_in_days] if rule.key? :exp_in_days Id rule[:id] if rule.key? :id NoncurrentVersionExpirationInDays rule[:non_exp_in_days] if rule.key? :non_exp_in_days NoncurrentVersionTransitions noncurrent_transitions unless noncurrent_transitions.empty? Prefix rule[:prefix] if rule.key? :prefix Status status Transitions transitions unless transitions.empty? } end return rules if rules.empty? _{ Rules rules } end
_s3_lifecycle_noncurrent_version_transition(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 139 def _s3_lifecycle_noncurrent_version_transition(args) (args[:noncurrent_version_transitions] || []).collect do |transition| _{ StorageClass _s3_to_lifecycle_storage(transition[:storage]) TransitionInDays transition[:in_days] } end end
_s3_lifecycle_transition(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 148 def _s3_lifecycle_transition(args) (args[:transitions] || []).collect do |transition| _{ StorageClass _s3_to_lifecycle_storage(transition[:storage]) TransitionDate _timestamp_utc(transition[:date]) if transition.key? :date TransitionInDays transition[:in_days] } end end
_s3_logging(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 158 def _s3_logging(args) logging = args[:logging] || {} return logging if logging.empty? _{ DestinationBucketName logging[:destination] LogFilePrefix logging[:prefix] || "" } end
_s3_notification(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 168 def _s3_notification(args) notification = args[:notification] || {} return notification if notification.empty? lambda = _s3_notification_configuration(notification, :lambda) queue = _s3_notification_configuration(notification, :queue) topic = _s3_notification_configuration(notification, :topic) _{ LambdaConfigurations lambda unless lambda.empty? QueueConfigurations queue unless queue.empty? TopicConfigurations topic unless topic.empty? } end
_s3_notification_configuration(args, key)
click to toggle source
# File lib/kumogata/template/s3.rb, line 183 def _s3_notification_configuration(args, key) return {} unless args.key? key.to_sym args[key.to_sym].collect do |value| _{ Event _s3_to_notification_event_type(value[:event]) Filter _{ S3Key _{ Rules value[:filters].collect{|v| filter = [] v.each_pair do |kk, vv| filter << _{ Name kk Value vv } end filter }.flatten } } if value.key? :filters case key.to_sym when :lambda Function _ref_attr_string("function", "Arn", value, "lambda function", "arn") when :queue Queue _ref_attr_string("queue", "Arn", value, "queue") when :topic Topic _ref_string("topic", value, "topic") end } end end
_s3_replication(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 215 def _s3_replication(args) replication = args[:replication] || {} return replication if replication.empty? rules = _s3_replication_rules(replication) _{ Role replication[:role] Rules rules } end
_s3_replication_rules(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 227 def _s3_replication_rules(args) (args[:rules] || []).collect do |rule| destination = _s3_replication_rules_destination(rule[:destination]) _{ Destination destination Id rule[:id] Prefix rule[:prefix] Status rule[:status] } end end
_s3_replication_rules_destination(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 239 def _s3_replication_rules_destination(args) _{ Bucket args[:bucket] StorageClass args[:storage] } end
_s3_to_access(value)
click to toggle source
# File lib/kumogata/template/s3.rb, line 21 def _s3_to_access(value) return "Private" if value.nil? case value when "auth read" "AuthenticatedRead" when "aws exec read" "AwsExecRead" when "owner read" "BucketOwnerRead" when "owner full" "BucketOwnerFullControl" when "log delivery write" "LogDeliveryWrite" when "private" "Private" when "public read" "PublicRead" when "public read write" "PublicReadWrite" else value end end
_s3_to_deletion_policy(value)
click to toggle source
# File lib/kumogata/template/s3.rb, line 6 def _s3_to_deletion_policy(value) return "Retain" if value.nil? case value when "delete" "Delete" when "retain" "Retain" when "shapshot" "Snapshot" else _valid_values(value, %w( Delete Retain Snapshot ), "Retain") end end
_s3_to_lifecycle_move_to_glacier(exp_in_days = 1, trans_in_days = 1, prefix = "")
click to toggle source
# File lib/kumogata/template/s3.rb, line 55 def _s3_to_lifecycle_move_to_glacier(exp_in_days = 1, trans_in_days = 1, prefix = "") lifecycle = { exp_in_days: exp_in_days, id: "lifecycle rule - move to glacier expiration / transition in days: #{exp_in_days} / #{trans_in_days}", transitions: [ { storage: "glacier", in_days: trans_in_days }, ], } lifecycle[:prefix] = prefix unless prefix.empty? lifecycle end
_s3_to_lifecycle_storage(value)
click to toggle source
# File lib/kumogata/template/s3.rb, line 46 def _s3_to_lifecycle_storage(value) case value when "ia" "STANDARD_IA" else "GLACIER" end end
_s3_to_notification_event_type(value)
click to toggle source
# File lib/kumogata/template/s3.rb, line 67 def _s3_to_notification_event_type(value) type = case value when 'create all', 'new' 'ObjectCreated:*' when 'put' 'ObjectCreated:Put' when 'post' 'ObjectCreated:Post' when 'copy' 'ObjectCreated:Copy' when 'upload' 'ObjectCreated:CompleteMultipartUpload' when 'delete all', 'remove all' 'ObjectRemoved:*' when 'delete' 'ObjectRemoved:Delete' when 'delete marker' 'ObjectRemoved:DeleteMarkerCreated' when 'lost' 'ReducedRedundancyLostObject' end "s3:#{type}" end
_s3_versioning(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 246 def _s3_versioning(args) return "" unless args.key? :versioning status = if _bool("versioning", args, false) "Enabled" else "Suspended" end _{ Status status } end
_s3_website(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 260 def _s3_website(args) website = args[:website] || "" return website if website.empty? redirect = _s3_website_redirect_all_request(website) routing = _s3_website_routing_rules(website) _{ ErrorDocument website[:error] || "error.html" IndexDocument website[:index] || "index.html" RedirectAllRequestsTo redirect unless redirect.empty? RoutingRules routing unless routing.empty? } end
_s3_website_redirect_all_request(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 275 def _s3_website_redirect_all_request(args) redirect = args[:redirect] || {} return redirect if redirect.empty? _{ HostName redirect[:hostname] Protocol _valid_values(redirect[:protocol], %w( http https ), "http") } end
_s3_website_routing_rules(args)
click to toggle source
# File lib/kumogata/template/s3.rb, line 285 def _s3_website_routing_rules(args) (args[:routing] || []).collect do |route| _{ RedirectRule do redirect = route[:redirect] || {} HostName redirect[:host] if redirect.key? :host HttpRedirectCode redirect[:http] if redirect.key? :http Protocol redirect[:protocol] if redirect.key? :protocol ReplaceKeyPrefixWith redirect[:replace_key_prefix] if redirect.key? :replace_key_prefix ReplaceKeyWith redirect[:replace_key_with] if redirect.key? :replace_key_with end RoutingRuleCondition do routing = route[:routing] || {} HttpErrorCodeReturnedEquals routing[:http] KeyPrefixEquals routing[:key_prefix] end } end end
_select(index, list)
click to toggle source
# File lib/kumogata/template/helper.rb, line 242 def _select(index, list) _{ Fn__Select [ index.to_s, list ] } end
_sns_subscription_list(args)
click to toggle source
# File lib/kumogata/template/sns.rb, line 21 def _sns_subscription_list(args) (args[:subscription] || []).collect do |v| if v.is_a? String protocol = "email" endpoint = v else protocol = _sns_to_protocol(v[:protocol]) endpoint = _sns_to_endpoint(protocol, v[:endpoint]) end _{ Endpoint endpoint Protocol protocol } end end
_sns_to_endpoint(protocol, value)
click to toggle source
# File lib/kumogata/template/sns.rb, line 12 def _sns_to_endpoint(protocol, value) case protocol when "lambda", "sqs" _attr_string(value, "Arn") else value end end
_sns_to_protocol(value)
click to toggle source
# File lib/kumogata/template/sns.rb, line 6 def _sns_to_protocol(value) _valid_values(value, %w( http https email email-json sms sqs application lambda ), "email") end
_split(name, delimiter = ",")
click to toggle source
# File lib/kumogata/template/helper.rb, line 246 def _split(name, delimiter = ",") _{ Fn__Split [ delimiter, name ] } end
_sub(name, mappings = [])
click to toggle source
# File lib/kumogata/template/helper.rb, line 250 def _sub(name, mappings = []) if mappings.empty? _{ Fn__Sub name } else array = [ name ] mappings.each do |mapping| mapping.each_pair do |key, value| _sub = {} _sub.store(_resource_name(key), _ref_string('', { ref_: value })) array << _sub end end _{ Fn__Sub array } end end
_sub_service(service)
click to toggle source
# File lib/kumogata/template/helper.rb, line 266 def _sub_service(service) _sub("#{service}.#{_var_pseudo('region')}.#{DOMAIN}") end
_tag(args)
click to toggle source
# File lib/kumogata/template/helper.rb, line 331 def _tag(args) key = args[:key].to_s || '' value = args[:value] || '' is_ref = (key =~ /^ref_.*/) ? true : false _{ Key _resource_name(key.gsub(/^ref_/, '')) Value is_ref ? _ref(_resource_name(value)) : value } end
_timestamp_utc(time = Time.now, type = '')
click to toggle source
# File lib/kumogata/template/helper.rb, line 399 def _timestamp_utc(time = Time.now, type = '') format = case type when "cron" "%M %H %d %m %w" else "%Y-%m-%dT%H:%M:%SZ" end time.utc.strftime(format) end
_timestamp_utc_duration(minute, hour = nil, second = nil)
click to toggle source
# File lib/kumogata/template/helper.rb, line 414 def _timestamp_utc_duration(minute, hour = nil, second = nil) duration = "PT" duration += "#{hour}H" unless hour.nil? duration += "#{minute}M" duration += "#{second}S" unless second.nil? duration end
_timestamp_utc_from_string(time, type = '')
click to toggle source
# File lib/kumogata/template/helper.rb, line 410 def _timestamp_utc_from_string(time, type = '') _timestamp_utc(Time.strptime(time, "%Y-%m-%d %H:%M"), type) end
_valid_numbers(value, min = 0, max = 0, default = nil)
click to toggle source
# File lib/kumogata/template/helper.rb, line 96 def _valid_numbers(value, min = 0, max = 0, default = nil) return default if value.nil? number = value.to_i (min <= number and number <= max) ? number : default end
_valid_values(value, values, default = nil)
click to toggle source
# File lib/kumogata/template/helper.rb, line 90 def _valid_values(value, values, default = nil) return default if value.nil? values.collect{|v| return v if v =~ /^#{value}$/i } default end
_value(name, value, default = "*")
click to toggle source
# File lib/kumogata/template/iam.rb, line 225 def _value(name, value, default = "*") if value.key? "ref_#{name}".to_sym { ref_: value["ref_#{name}".to_sym] } elsif value.key? "import_#{name}".to_sym { import_: value["import_#{name}".to_sym] } else value[name.to_sym] || default end end
_var(value)
click to toggle source
# File lib/kumogata/template/helper.rb, line 366 def _var(value) "${#{value}}" end
_var_pseudo(type)
click to toggle source
# File lib/kumogata/template/helper.rb, line 166 def _var_pseudo(type) "${AWS::#{_pseudo(type)}}" end
_window_time(service, start_time)
click to toggle source
# File lib/kumogata/template/helper.rb, line 439 def _window_time(service, start_time) start_time = start_time.utc format = "%H:%M" case service when "elasticache" # 60 min end_time = start_time + (60 * 60) when "rds" # 30 min end_time = start_time + (60 * 30) end "#{start_time.strftime(format)}-#{end_time.strftime(format)}" end