61425f35a4e4ca0ef967ce5d941d12a4fd1c8595
[osm/devops.git] / charms / layers / ansible-charm / reactive / ansible_charm.py
1 # OSM devops/charms - Ansible charm inside OSM devops
2 #
3 # Copyright 2017-2018 Universidad Carlos III de Madrid
4 # Copyright 2018 Altran
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17
18 from charmhelpers.core.hookenv import (
19 action_get,
20 action_fail,
21 action_set,
22 config,
23 status_set,
24 )
25
26 from charms.reactive import (
27 remove_state as remove_flag,
28 set_state as set_flag,
29 when,
30 )
31 import charms.sshproxy
32
33 from subprocess import (
34 Popen,
35 CalledProcessError,
36 PIPE,
37 )
38
39 #from charms.ansible import apply_playbook
40 import os, fnmatch
41 import subprocess
42
43 cfg = config()
44
45
46 # Sets the status of the charm to show in OSM: configured
47 @when('config.changed')
48 def config_changed():
49 set_flag('ansible-charm.configured')
50 status_set('active', 'ready!')
51 return
52
53
54 # Edits ansible config files and executes ansible-playbook
55 @when('ansible-charm.configured')
56 @when('actions.ansible-playbook')
57 def ansible_playbook():
58 try:
59 # Retrieve the ssh parameter
60 cfg = config()
61 # edit ansible hosts file with the VNF parameters
62 h = open("/etc/ansible/hosts", "wt")
63 h.write("[test]\n")
64 h1 = "{} ansible_connection=ssh ansible_ssh_user={} ansible_ssh_pass={} ansible_python_interpreter=/usr/bin/python3\n".format(cfg['ssh-hostname'],cfg['ssh-username'],cfg['ssh-password'])
65 h.write(h1)
66 h.close()
67 # edit ansible config to enable ssh connection with th VNF
68 c = open("/etc/ansible/ansible.cfg", "wt")
69 c.write("[defaults]\n")
70 c.write("host_key_checking = False\n")
71 c.close()
72 # execute the ansible playbook
73 path = find('playbook.yaml','/var/lib/juju/agents/')
74 call = ['ansible-playbook', path]
75 subprocess.check_call(call)
76 except Exception as e:
77 action_fail('command failed: {}, errors: {}'.format(e, e.output))
78 remove_flag('actions.ansible-playbook')
79 return
80 finally:
81 remove_flag('actions.ansible-playbook')
82
83
84 # Function to find the playbook path
85 def find(pattern, path):
86 result = ''
87 for root, dirs, files in os.walk(path):
88 for name in files:
89 if fnmatch.fnmatch(name, pattern):
90 result = os.path.join(root, name)
91 return result