summaryrefslogtreecommitdiffstats
path: root/roles/lib_openshift/library/oc_secret.py
diff options
context:
space:
mode:
Diffstat (limited to 'roles/lib_openshift/library/oc_secret.py')
-rw-r--r--roles/lib_openshift/library/oc_secret.py98
1 files changed, 68 insertions, 30 deletions
diff --git a/roles/lib_openshift/library/oc_secret.py b/roles/lib_openshift/library/oc_secret.py
index b2a689def..526474f17 100644
--- a/roles/lib_openshift/library/oc_secret.py
+++ b/roles/lib_openshift/library/oc_secret.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -338,6 +339,17 @@ class Yedit(object):
return data
+ @staticmethod
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ tmp_filename = filename + '.yedit'
+
+ with open(tmp_filename, 'w') as yfd:
+ yfd.write(contents)
+
+ os.rename(tmp_filename, filename)
+
def write(self):
''' write to file '''
if not self.filename:
@@ -346,15 +358,11 @@ class Yedit(object):
if self.backup and self.file_exists():
shutil.copy(self.filename, self.filename + '.orig')
- tmp_filename = self.filename + '.yedit'
- with open(tmp_filename, 'w') as yfd:
- # pylint: disable=no-member
- if hasattr(self.yaml_dict, 'fa'):
- self.yaml_dict.fa.set_block_style()
-
- yfd.write(yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
+ # pylint: disable=no-member
+ if hasattr(self.yaml_dict, 'fa'):
+ self.yaml_dict.fa.set_block_style()
- os.rename(tmp_filename, self.filename)
+ Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
return (True, self.yaml_dict)
@@ -751,7 +759,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -762,7 +770,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -786,7 +795,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -829,7 +838,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -1010,32 +1019,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
+ @staticmethod
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
@@ -1411,7 +1449,7 @@ class OCSecret(OpenShiftCLI):
def create(self, files=None, contents=None):
'''Create a secret '''
if not files:
- files = Utils.create_files_from_contents(contents)
+ files = Utils.create_tmp_files_from_contents(contents)
secrets = ["%s=%s" % (sfile['name'], sfile['path']) for sfile in files]
cmd = ['secrets', 'new', self.name]
@@ -1444,7 +1482,7 @@ class OCSecret(OpenShiftCLI):
This is accomplished by passing -ojson. This will most likely change in the future
'''
if not files:
- files = Utils.create_files_from_contents(contents)
+ files = Utils.create_tmp_files_from_contents(contents)
secrets = ["%s=%s" % (sfile['name'], sfile['path']) for sfile in files]
cmd = ['-ojson', 'secrets', 'new', self.name]
@@ -1495,7 +1533,7 @@ class OCSecret(OpenShiftCLI):
if params['files']:
files = params['files']
elif params['contents']:
- files = Utils.create_files_from_contents(params['contents'])
+ files = Utils.create_tmp_files_from_contents(params['contents'])
else:
return {'failed': True,
'msg': 'Either specify files or contents.'}
@@ -1509,7 +1547,7 @@ class OCSecret(OpenShiftCLI):
return {'changed': True,
'msg': 'Would have performed a create.'}
- api_rval = ocsecret.create(params['files'], params['contents'])
+ api_rval = ocsecret.create(files, params['contents'])
# Remove files
if files and params['delete_after']: