Module: AnsibleSpec

Defined in:
lib/ansible_spec.rb,
lib/ansible_spec/version.rb,
lib/ansible_spec/load_ansible.rb

Overview

Defined Under Namespace

Classes: TermColor

Constant Summary collapse

VERSION =
"0.2.15"

Class Method Summary collapse

Class Method Details

.find_group_vars_file(hosts_childrens, hosts) ⇒ Object



366
367
368
369
370
371
# File 'lib/ansible_spec/load_ansible.rb', line 366

def self.find_group_vars_file(hosts_childrens, hosts)
    target_host = hosts_childrens.select { |key, value|
      value["children"].include?(hosts)
    }
    target_host.keys[0]
end

.flatten_role(roles) ⇒ Object

flatten roles (Issue 29) param: Array

e.g. ["nginx"]
e.g. [{"role"=>"nginx"}]
e.g. [{"role"=>"nginx", "dir"=>"/opt/b", "port"=>5001}]

return: Array

e.g.["nginx"]


252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/ansible_spec/load_ansible.rb', line 252

def self.flatten_role(roles)
  ret = Array.new
  if roles
    roles.each do |role|
      if role.is_a?(String)
        ret << role
      elsif role.is_a?(Hash)
        ret << role["role"] if role.has_key?("role")
      end
    end
  end
  return ret
end

.get_dynamic_inventory(file) ⇒ Object

param filename

{"databases":{"hosts":["aaa.com","bbb.com"],"vars":{"a":true}}}
{"webservers":["aaa.com","bbb.com"]}

return: Hash => “aaa.com”, “port” => 22, => “bbb.com”, “port” => 22]}



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/ansible_spec/load_ansible.rb', line 101

def self.get_dynamic_inventory(file)
  if file[0] == "/"
    file_path = file
  else
    file_path = "./#{file}"
  end
  res = Hash.new
  so, se, st = Open3.capture3(file_path)
  dyn_inv = Oj.load(so.to_s)

  res["hosts_childrens"] = dyn_inv.select do |property, value|
    value.instance_of?(Hash) && value.has_key?("children")
  end

  if dyn_inv.key?('_meta')
    # assume we have an ec2.py created dynamic inventory
    dyn_inv = dyn_inv.tap{ |h| h.delete("_meta") }
  end
  dyn_inv.each{|k,v|
    res["#{k.to_s}"] = Array.new unless res.has_key?("#{k.to_s}")
    if v.is_a?(Array)
      # {"webservers":["aaa.com","bbb.com"]}
      v.each {|host|
        res["#{k.to_s}"] << {"uri"=> host, "port"=> 22}
      }
    elsif v.has_key?("hosts") && v['hosts'].is_a?(Array)
      v['hosts'].each {|host|
        res["#{k.to_s}"] << {"uri"=> host, "port"=> 22}
      }
    end
  }
  return res
end

.get_hash_behaviourObject

param: none return: hash_behaviour



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/ansible_spec/load_ansible.rb', line 280

def self.get_hash_behaviour()
  f = '.ansiblespec'
  y = nil
  if File.exist?(f)
    y = YAML.load_file(f)
  end
  hash_behaviour = 'replace'
  if ENV["HASH_BEHAVIOUR"]
    hash_behaviour = ENV["HASH_BEHAVIOUR"]
  elsif y.is_a?(Array) && y[0]['hash_behaviour']
    hash_behaviour = y[0]['hash_behaviour']
  end
  if !['replace','merge'].include?(hash_behaviour)
    puts "Error: hash_behaviour '" + hash_behaviour + "' should be 'replace' or 'merge' See https://github.com/volanja/ansible_spec"
    exit 1
  end
  return hash_behaviour
end

.get_inventory_param(line) ⇒ Object

param ansible_ssh_port=22 return: hash



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/ansible_spec/load_ansible.rb', line 137

def self.get_inventory_param(line)
  host = Hash.new
  # 初期値
  host['name'] = line
  host['port'] = 22
  if line.include?(":") # 192.168.0.1:22
    host['uri']  = line.split(":")[0]
    host['port'] = line.split(":")[1].to_i
    return host
  end
  # 192.168.0.1 ansible_ssh_port=22
  line.split.each{|v|
    unless v.include?("=")
      host['uri'] = v
    else
      key,value = v.split("=")
      host['port'] = value.to_i if key == "ansible_ssh_port"
      host['private_key'] = value if key == "ansible_ssh_private_key_file"
      host['user'] = value if key == "ansible_ssh_user"
      host['uri'] = value if key == "ansible_ssh_host"
      host['pass'] = value if key == "ansible_ssh_pass"
      host['connection'] = value if key == "ansible_connection"
    end
  }
  return host
end

.get_parent(hash, search, k) ⇒ Object

param hash href=""192.168.0.103"">server”=>, “databases”=>, “pg:children”=>[“server”, “databases”] param search “:children” param k “pg:children” return href=""192.168.0.103"">server”=>, “databases”=>, “pg”=>[“192.168.0.103”, “192.168.0.104”]



86
87
88
89
90
91
92
93
94
95
# File 'lib/ansible_spec/load_ansible.rb', line 86

def self.get_parent(hash,search,k)
  k_parent = k.gsub(search,'')
  arry = Array.new
  hash["#{k}"].each{|group|
    arry = arry + hash["#{group}"]
  }
  h = Hash.new
  h["#{k_parent}"] = arry
  return h
end

.get_propertiesObject

return: json “hosts”=>, “user”=>“root”, “roles”=>[“nginx”, “mariadb”]



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/ansible_spec/load_ansible.rb', line 332

def self.get_properties()
  playbook, inventoryfile = load_ansiblespec

  # load inventory file and playbook hosts mapping
  hosts = load_targets(inventoryfile)
  properties = load_playbook(playbook)
  properties.each do |var|
    var["hosts_childrens"] = hosts["hosts_childrens"]
    var["group"] = var["hosts"]
    if var["hosts"].to_s == "all"
      var["hosts"] = hosts.values.flatten
    elsif hosts.has_key?("#{var["hosts"]}")
      var["hosts"] = hosts["#{var["hosts"]}"]
    elsif var["hosts"].instance_of?(Array)
      tmp_host = var["hosts"]
      var["hosts"] = []
      tmp_host.each do |v|
        if hosts.has_key?("#{v}")
          hosts["#{v}"].map {|target_server| target_server["hosts"] = v}
          var["hosts"].concat hosts["#{v}"]
        end
      end 
      if var["hosts"].size == 0 
        properties = properties.compact.reject{|e| e["hosts"].length == 0}
        #puts "#{var["name"]} roles no hosts matched for #{var["hosts"]}"
      end
    else
      puts "no hosts matched for #{var["hosts"]}"
      var["hosts"] = []
    end
  end
  return properties
end

.get_variables(host, group_idx, hosts = nil) ⇒ Object



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/ansible_spec/load_ansible.rb', line 373

def self.get_variables(host, group_idx, hosts=nil)
  vars = {}
  p = self.get_properties

  # roles default
  p[group_idx]['roles'].each do |role|
    vars = load_vars_file(vars ,"roles/#{role}/defaults/main.yml")
  end

  # all group
  vars = load_vars_file(vars ,'group_vars/all', true)

  # each group vars
  if p[group_idx].has_key?('group')
    vars = load_vars_file(vars ,"group_vars/#{p[group_idx]['group']}", true)
  end

  # each host vars
  vars = load_vars_file(vars ,"host_vars/#{host}", true)

  # site vars
  if p[group_idx].has_key?('vars')
    vars = merge_variables(vars, p[group_idx]['vars'])
  end

  # roles vars
  p[group_idx]['roles'].each do |role|
    vars = load_vars_file(vars ,"roles/#{role}/vars/main.yml")
  end

  # multiple host and children dependencies group vars
  unless hosts.nil? || p[group_idx]["hosts_childrens"].nil?
    hosts_childrens = p[group_idx]["hosts_childrens"]
    next_find_target = hosts
    while(!next_find_target.nil? && hosts_childrens.size > 0)
      vars = load_vars_file(vars ,"group_vars/#{next_find_target}", true)
      group_vars_file = find_group_vars_file(hosts_childrens,next_find_target)
      next_find_target = group_vars_file
      hosts_childrens.delete(group_vars_file)
    end
  end

  return vars

end

.load_ansiblespecObject

param: none return: playbook, inventoryfile



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/ansible_spec/load_ansible.rb', line 166

def self.load_ansiblespec()
  f = '.ansiblespec'
  y = nil
  if File.exist?(f)
    y = YAML.load_file(f)
  end
  if ENV["PLAYBOOK"]
    playbook = ENV["PLAYBOOK"]
  elsif y.is_a?(Array) && y[0]['playbook']
    playbook = y[0]['playbook']
  else
    playbook = 'site.yml'
  end
  if ENV["INVENTORY"]
    inventoryfile = ENV["INVENTORY"]
  elsif y.is_a?(Array) && y[0]['inventory']
    inventoryfile = y[0]['inventory']
  else
    inventoryfile = 'hosts'
  end
  if File.exist?(playbook) == false
    puts 'Error: ' + playbook + ' is not Found. create site.yml or ./.ansiblespec  See https://github.com/volanja/ansible_spec'
    exit 1
  elsif File.exist?(inventoryfile) == false
    puts 'Error: ' + inventoryfile + ' is not Found. create hosts or ./.ansiblespec  See https://github.com/volanja/ansible_spec'
    exit 1
  end
  return playbook, inventoryfile
end

.load_dependencies(role) ⇒ Object

param: role return: [“role1”, “role2”]



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/ansible_spec/load_ansible.rb', line 198

def self.load_dependencies(role)
  role_queue = [role]
  deps = []
  until role_queue.empty?
    role = role_queue.pop()
    path = File.join("./", "roles", role, "meta", "main.yml")

    if File.exist?(path)
      new_deps = YAML.load_file(path).fetch("dependencies", []).map { |h|
        h["role"]
      }
      role_queue.concat(new_deps)
      deps.concat(new_deps)
    end
  end
  return deps
end

.load_playbook(f) ⇒ Object

param: playbook return: json

{"name"=>"Ansible-Sample-TDD", "hosts"=>"server", "user"=>"root", "roles"=>["nginx", "mariadb"]}


219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/ansible_spec/load_ansible.rb', line 219

def self.load_playbook(f)
  playbook = YAML.load_file(f)

  # e.g. comment-out
  if playbook === false
    puts 'Error: No data in site.yml'
    exit
  end
  properties = Array.new
  playbook.each do |site|
    if site.has_key?("include")
      properties.push YAML.load_file(site["include"])[0]
    else
      properties.push site
    end
  end
  properties.each do |property|
    property["roles"] = flatten_role(property["roles"])
  end
  if name_exist?(properties)
    return properties
  else
    fail "Please insert name on playbook"
  end
end

.load_targets(file) ⇒ Object

param: inventory file of Ansible return: Hash => [“192.168.0.1”,“192.168.0.2”] return: Hash => [{“name” => “192.168.0.1”,“uri” => “192.168.0.1”, “port” => 22,…]}



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/ansible_spec/load_ansible.rb', line 12

def self.load_targets(file)
  if File.executable?(file)
    return get_dynamic_inventory(file)
  end
  f = File.open(file).read
  groups = Hash.new
  group = ''
  hosts = Hash.new
  hosts.default = Hash.new
  f.each_line{|line|
    line = line.chomp
    # skip
    next if line.start_with?('#') #comment
    next if line.empty? == true   #null

    # get group
    if line.start_with?('[') && line.end_with?(']')
      group = line.gsub('[','').gsub(']','')
      groups["#{group}"] = Array.new
      next
    end

    # get host
    host_name = line.split[0]
    if group.empty? == false
      if groups.has_key?(line)
        groups["#{group}"] << line
        next
      elsif host_name.include?("[") && host_name.include?("]")
        # www[01:50].example.com
        # db-[a:f].example.com
        hostlist_expression(line,":").each{|h|
          host = hosts[h.split[0]]
          groups["#{group}"] << get_inventory_param(h).merge(host)
        }
        next
      else
        # 1つのみ、かつ:を含まない場合
        # 192.168.0.1
        # 192.168.0.1 ansible_ssh_host=127.0.0.1 ...
        host = hosts[host_name]
        groups["#{group}"] << get_inventory_param(line).merge(host)
        next
      end
    else
      if host_name.include?("[") && host_name.include?("]")
        hostlist_expression(line, ":").each{|h|
          hosts[h.split[0]] = get_inventory_param(h)
        }
      else
        hosts[host_name] = get_inventory_param(line)
      end
    end
  }

  # parse children [group:children]
  search = Regexp.new(":children".to_s)
  groups.keys.each{|k|
    unless (k =~ search).nil?
      # get group parent & merge parent
      groups.merge!(get_parent(groups,search,k))
      # delete group children
      if groups.has_key?("#{k}") && groups.has_key?("#{k.gsub(search,'')}")
        groups.delete("#{k}")
      end
    end
  }
  return groups
end

.load_vars_file(vars, path, check_no_ext = false) ⇒ Object

param: hash param: variable file param: flag to extention

true:  .yml extension is optional
false: must have .yml extention


304
305
306
307
308
309
310
311
312
313
314
# File 'lib/ansible_spec/load_ansible.rb', line 304

def self.load_vars_file(vars, path, check_no_ext = false)
  vars_file = path
  if check_no_ext && !File.exist?(vars_file)
    vars_file = path+".yml"
  end
  if File.exist?(vars_file)
    yaml = YAML.load_file(vars_file)
    vars = merge_variables(vars, yaml)
  end
  return vars
end

.mainObject



12
13
14
15
16
17
# File 'lib/ansible_spec.rb', line 12

def self.main()
  safe_create_spec_helper
  safe_create_rakefile
  safe_create_ansiblespec
  safe_create_rspec
end

.merge_variables(vars, hash) ⇒ Object

param: target hash param: be merged hash



318
319
320
321
322
323
324
325
326
327
328
# File 'lib/ansible_spec/load_ansible.rb', line 318

def self.merge_variables(vars, hash)
  hash_behaviour = get_hash_behaviour()
  if hash.kind_of?(Hash)
    if hash_behaviour=="merge"
      vars.deep_merge!(hash)
    else
      vars.merge!(hash)
    end
  end
  return vars
end

.name_exist?(array) ⇒ Boolean

Issue 27 param: array return: boolean

true: name is exist on playbook
false: name is not exist on playbook

Returns:

  • (Boolean)


272
273
274
275
276
# File 'lib/ansible_spec/load_ansible.rb', line 272

def self.name_exist?(array)
  array.each do |site|
    return site.has_key?("name") ? true : false
  end
end

.safe_create_ansiblespecObject



38
39
40
41
42
43
44
# File 'lib/ansible_spec.rb', line 38

def self.safe_create_ansiblespec
  content = File.open(File.dirname(__FILE__) + "/../lib/src/.ansiblespec").read
  safe_touch(".ansiblespec")
  File.open(".ansiblespec", 'w') do |f|
    f.puts content
  end
end

.safe_create_rakefileObject



30
31
32
33
34
35
36
# File 'lib/ansible_spec.rb', line 30

def self.safe_create_rakefile
  content = File.open(File.dirname(__FILE__) + "/../lib/src/Rakefile").read
  safe_touch("Rakefile")
  File.open("Rakefile", 'w') do |f|
    f.puts content
  end
end

.safe_create_rspecObject



46
47
48
49
50
51
52
# File 'lib/ansible_spec.rb', line 46

def self.safe_create_rspec
  content = File.open(File.dirname(__FILE__) + "/../lib/src/.rspec").read
  safe_touch(".rspec")
  File.open(".rspec", 'w') do |f|
    f.puts content
  end
end

.safe_create_spec_helperObject



20
21
22
23
24
25
26
27
28
# File 'lib/ansible_spec.rb', line 20

def self.safe_create_spec_helper
  content = File.open(File.dirname(__FILE__) + "/../lib/src/spec/spec_helper.rb").read
  safe_mkdir("spec")
  safe_touch("spec/spec_helper.rb")
  File.open("spec/spec_helper.rb", 'w') do |f|
    f.puts content
  end

end

.safe_mkdir(dir) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/ansible_spec.rb', line 54

def self.safe_mkdir(dir)
  unless FileTest.exist?("#{dir}")
    FileUtils.mkdir_p("#{dir}")
    TermColor.green
    puts "\t\tcreate\t#{dir}"
    TermColor.reset
  else
    TermColor.red
    puts "\t\texists\t#{dir}"
    TermColor.reset
  end
end

.safe_touch(file) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/ansible_spec.rb', line 67

def self.safe_touch(file)
  unless File.exists? "#{file}"
    File.open("#{file}", 'w') do |f|
        #f.puts content
    end
    TermColor.green
    puts "\t\tcreate\t#{file}"
    TermColor.reset
  else 
    TermColor.red
    puts "\t\texists\t#{file}"
    TermColor.reset
  end
end