2 # Copyright 2019 Whitestack, LLC
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
16 # For those usages not covered by the Apache License, Version 2.0 please
17 # contact: esousa@whitestack.com or glavado@whitestack.com
19 {%- if license is defined -%}
20 # Copyright {{ license.year }} {{ license.company }}
22 # Licensed under the Apache License, Version 2.0 (the "License"); you may
23 # not use this file except in compliance with the License. You may obtain
24 # a copy of the License at
26 # http://www.apache.org/licenses/LICENSE-2.0
28 # Unless required by applicable law or agreed to in writing, software
29 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
30 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
31 # License for the specific language governing permissions and limitations
34 # For those usages not covered by the Apache License, Version 2.0 please
35 # contact: {{ license.email }}
43 from charmhelpers.core.hookenv import config
46 def create_hosts(cfg, hosts):
47 inventory_path = '/etc/ansible/hosts'
49 with open(inventory_path, 'w') as f:
50 f.write('[{}]\n'.format(hosts))
51 h1 = '{0} ansible_connection=ssh ansible_ssh_user={1} ansible_ssh_pass={2} ' \
52 'ansible_python_interpreter=/usr/bin/python3\n'.format(cfg['ssh-hostname'], cfg['ssh-username'],
57 def create_ansible_cfg():
58 ansible_config_path = '/etc/ansible/ansible.cfg'
60 with open(ansible_config_path, 'w') as f:
61 f.write('[defaults]\n')
62 f.write('host_key_checking = False\n')
63 # logs playbook execution attempts to the specified path
64 f.write('log_path = /var/log/ansible.log\n')
66 # Function to find the playbook path
67 def find(pattern, path):
69 for root, dirs, files in os.walk(path):
71 if fnmatch.fnmatch(name, pattern):
72 result = os.path.join(root, name)
76 def execute_playbook(playbook_file, vars_dict=None):
77 playbook_path = find(playbook_file, '/var/lib/juju/agents/')
81 with open(playbook_path, 'r') as f:
82 playbook_data = yaml.load(f)
85 if 'hosts' in playbook_data[0].keys() and playbook_data[0]['hosts']:
86 hosts = playbook_data[0]['hosts']
89 create_hosts(cfg, hosts)
91 call = 'ansible-playbook %s ' % playbook_path
93 if vars_dict and isinstance(vars_dict, dict) and len(vars_dict) > 0:
94 call += '--extra-vars '
97 for v in vars_dict.items():
98 string_var += '%s=%s ' % v
100 string_var = string_var.strip()
101 call += '"%s"' % string_var
104 result = subprocess.check_output(call, shell=True)