dynamicweb/utils/tasks.py

36 lines
1.2 KiB
Python
Raw Normal View History

2017-08-28 06:55:39 +00:00
import cdist
import tempfile
2017-08-28 09:40:59 +00:00
from cdist.integration import configure_hosts_simple
from celery.utils.log import get_task_logger
from django.conf import settings
from dynamicweb.celery import app
2017-08-28 06:55:39 +00:00
logger = get_task_logger(__name__)
@app.task(bind=True, max_retries=settings.CELERY_MAX_RETRIES)
2017-08-28 09:40:59 +00:00
def save_ssh_key(self, hosts, keys):
2017-08-28 06:55:39 +00:00
"""
Saves ssh key into the VMs of a user using cdist
:param hosts: A list of hosts to be configured
:param keys: A list of keys to be added
"""
2017-08-28 09:40:59 +00:00
return_value = True
2017-08-29 16:15:23 +00:00
with tempfile.NamedTemporaryFile(delete=True) as tmp_manifest:
2017-08-28 09:40:59 +00:00
# Generate manifest to be used for configuring the hosts
2017-08-29 16:15:23 +00:00
lines_list = [' --key "{key}"\\\n'.format(key=key).encode('utf-8') for
key in keys]
lines_list.insert(0, b'__ssh_authorized_keys root \\\n')
tmp_manifest.writelines(lines_list)
tmp_manifest.flush()
2017-08-28 09:40:59 +00:00
try:
configure_hosts_simple(hosts,
tmp_manifest.name,
verbose=cdist.argparse.VERBOSE_TRACE)
except Exception as cdist_exception:
logger.error(cdist_exception)
return_value = False
return return_value