def generate_group_vars_all(self):
path = 'result/{}/group_vars/all'.format(self.grid_name)
variables = AutoDict()
hosts_entries = AutoDict()
with open('result/{}/infrastructure/terraform.tfstate'.format(
self.grid_name), 'r') as json_file:
json_data = json.load(json_file)
for module in json_data['modules']:
for resource, value in module['resources'].iteritems():
if value['type'] == 'aws_instance':
hostname = value['primary']['attributes'][
'private_dns'].split('.')[0]
host = '{}.node.{}'.format(hostname, self.grid_name)
ip = value['primary']['attributes']['private_ip']
hosts_entries['hosts'][str(host)] = str(ip)
variables['hosts'] = json.dumps(hosts_entries['hosts'])
variables['grid_name'] = self.current_grid.name
self._generate_template(path, variables)
vars_json = json.loads(self.current_config.vars)
vars_yaml = yaml.safe_dump(vars_json, default_flow_style=False)
with open(path, "a") as yaml_file:
yaml_file.write(vars_yaml)
python类safe_dump()的实例源码
def generate_group_vars_all(self):
path = 'result/{}/group_vars/all'.format(self.grid_name)
variables = AutoDict()
hosts_entries = AutoDict()
with open('result/{}/infrastructure/terraform.tfstate'.format(
self.grid_name), 'r') as json_file:
json_data = json.load(json_file)
for module in json_data['modules']:
for resource, value in module['resources'].iteritems():
if value['type'] == 'openstack_compute_instance_v2':
host = '{}.node.{}'.format(
value['primary']['attributes'][
'name'], self.grid_name)
ip = value['primary']['attributes']['network.0.fixed_ip_v4']
hosts_entries['hosts'][str(host)] = str(ip)
variables['hosts'] = json.dumps(hosts_entries['hosts'])
variables['grid_name'] = self.current_grid.name
self._generate_template(path, variables)
vars_json = json.loads(self.current_config.vars)
vars_yaml = yaml.safe_dump(vars_json, default_flow_style=False)
with open(path, "a") as yaml_file:
yaml_file.write(vars_yaml)
def export_conf(conf, conf_file, exclude=None):
"""Export configuration file."""
exclude = set() if exclude is None else set(exclude)
if not conf_file:
print('( ) No configuration file provided')
return
if op.isfile(conf_file):
print('(!) File "{0}" exists, skipping export'.format(conf_file))
return
with open(conf_file, 'w') as f:
# The dict() is also to get rid of the SemiFrozenDict
dumped = dict(item for item in conf.items()
if item[0] not in exclude)
f.write(yaml.safe_dump(dumped, default_flow_style=False, allow_unicode=True))
print('( ) File "{0}" created with configuration'.format(conf_file))
def create_enable_file(certpem, keypem, source_dir, dest_dir, tht_release):
output_dict = _open_yaml("{}environments/enable-tls.yaml".format(source_dir))
if tht_release not in ['master', 'newton']:
for key in output_dict["parameter_defaults"]["EndpointMap"]:
if output_dict["parameter_defaults"]["EndpointMap"][key]["host"] == "CLOUDNAME":
output_dict["parameter_defaults"]["EndpointMap"][key]["host"] = "IP_ADDRESS"
output_dict["parameter_defaults"]["SSLCertificate"] = certpem
output_dict["parameter_defaults"]["SSLKey"] = keypem
output_dict["resource_registry"]["OS::TripleO::NodeTLSData"] = \
"{}/puppet/extraconfig/tls/tls-cert-inject.yaml".format(source_dir)
with open("{}enable-tls.yaml".format(dest_dir), "w") as stream:
yaml.safe_dump(output_dict, stream, default_style='|')
def relation_set(relation_id=None, relation_settings=None, **kwargs):
"""Set relation information for the current unit"""
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--help"], universal_newlines=True)
if relation_id is not None:
relation_cmd_line.extend(('-r', relation_id))
settings = relation_settings.copy()
settings.update(kwargs)
for key, value in settings.items():
# Force value to be a string: it always should, but some call
# sites pass in things like dicts or numbers.
if value is not None:
settings[key] = "{}".format(value)
if accepts_file:
# --file was introduced in Juju 1.23.2. Use it by default if
# available, since otherwise we'll break if the relation data is
# too big. Ideally we should tell relation-set to read the data from
# stdin, but that feature is broken in 1.23.2: Bug #1454678.
with tempfile.NamedTemporaryFile(delete=False) as settings_file:
settings_file.write(yaml.safe_dump(settings).encode("utf-8"))
subprocess.check_call(
relation_cmd_line + ["--file", settings_file.name])
os.remove(settings_file.name)
else:
for key, value in settings.items():
if value is None:
relation_cmd_line.append('{}='.format(key))
else:
relation_cmd_line.append('{}={}'.format(key, value))
subprocess.check_call(relation_cmd_line)
# Flush cache of any relation-gets for local unit
flush(local_unit())
def relation_set(relation_id=None, relation_settings=None, **kwargs):
"""Set relation information for the current unit"""
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--help"], universal_newlines=True)
if relation_id is not None:
relation_cmd_line.extend(('-r', relation_id))
settings = relation_settings.copy()
settings.update(kwargs)
for key, value in settings.items():
# Force value to be a string: it always should, but some call
# sites pass in things like dicts or numbers.
if value is not None:
settings[key] = "{}".format(value)
if accepts_file:
# --file was introduced in Juju 1.23.2. Use it by default if
# available, since otherwise we'll break if the relation data is
# too big. Ideally we should tell relation-set to read the data from
# stdin, but that feature is broken in 1.23.2: Bug #1454678.
with tempfile.NamedTemporaryFile(delete=False) as settings_file:
settings_file.write(yaml.safe_dump(settings).encode("utf-8"))
subprocess.check_call(
relation_cmd_line + ["--file", settings_file.name])
os.remove(settings_file.name)
else:
for key, value in settings.items():
if value is None:
relation_cmd_line.append('{}='.format(key))
else:
relation_cmd_line.append('{}={}'.format(key, value))
subprocess.check_call(relation_cmd_line)
# Flush cache of any relation-gets for local unit
flush(local_unit())
def relation_set(relation_id=None, relation_settings=None, **kwargs):
"""Set relation information for the current unit"""
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--help"], universal_newlines=True)
if relation_id is not None:
relation_cmd_line.extend(('-r', relation_id))
settings = relation_settings.copy()
settings.update(kwargs)
for key, value in settings.items():
# Force value to be a string: it always should, but some call
# sites pass in things like dicts or numbers.
if value is not None:
settings[key] = "{}".format(value)
if accepts_file:
# --file was introduced in Juju 1.23.2. Use it by default if
# available, since otherwise we'll break if the relation data is
# too big. Ideally we should tell relation-set to read the data from
# stdin, but that feature is broken in 1.23.2: Bug #1454678.
with tempfile.NamedTemporaryFile(delete=False) as settings_file:
settings_file.write(yaml.safe_dump(settings).encode("utf-8"))
subprocess.check_call(
relation_cmd_line + ["--file", settings_file.name])
os.remove(settings_file.name)
else:
for key, value in settings.items():
if value is None:
relation_cmd_line.append('{}='.format(key))
else:
relation_cmd_line.append('{}={}'.format(key, value))
subprocess.check_call(relation_cmd_line)
# Flush cache of any relation-gets for local unit
flush(local_unit())
def yaml(self, output):
"""Output data in YAML format"""
import yaml
yaml.safe_dump(output, self.outfile)
def yaml_format(data):
return yaml.safe_dump(dict(data), default_flow_style=False, explicit_start=True, explicit_end=True)
def show(connect, **kwargs):
config = connect.get_config()
if config:
s = yaml.safe_dump(config, encoding='utf-8', allow_unicode=True)
sys.stdout.write(s)
else:
print "FastScore not configured (use 'fastscore config set')"
def dump_yaml(tables, outdir, outfilename):
stream = file(os.path.join(outdir, outfilename+'.yaml'), 'wb')
yaml.safe_dump(tables, stream, allow_unicode=True)
stream.close()
#
# Process files listed on command line, or all .xls files in current dir if no
# args given
#
def relation_set(relation_id=None, relation_settings=None, **kwargs):
"""Set relation information for the current unit"""
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--help"], universal_newlines=True)
if relation_id is not None:
relation_cmd_line.extend(('-r', relation_id))
settings = relation_settings.copy()
settings.update(kwargs)
for key, value in settings.items():
# Force value to be a string: it always should, but some call
# sites pass in things like dicts or numbers.
if value is not None:
settings[key] = "{}".format(value)
if accepts_file:
# --file was introduced in Juju 1.23.2. Use it by default if
# available, since otherwise we'll break if the relation data is
# too big. Ideally we should tell relation-set to read the data from
# stdin, but that feature is broken in 1.23.2: Bug #1454678.
with tempfile.NamedTemporaryFile(delete=False) as settings_file:
settings_file.write(yaml.safe_dump(settings).encode("utf-8"))
subprocess.check_call(
relation_cmd_line + ["--file", settings_file.name])
os.remove(settings_file.name)
else:
for key, value in settings.items():
if value is None:
relation_cmd_line.append('{}='.format(key))
else:
relation_cmd_line.append('{}={}'.format(key, value))
subprocess.check_call(relation_cmd_line)
# Flush cache of any relation-gets for local unit
flush(local_unit())
def relation_set(relation_id=None, relation_settings=None, **kwargs):
"""Set relation information for the current unit"""
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--help"], universal_newlines=True)
if relation_id is not None:
relation_cmd_line.extend(('-r', relation_id))
settings = relation_settings.copy()
settings.update(kwargs)
for key, value in settings.items():
# Force value to be a string: it always should, but some call
# sites pass in things like dicts or numbers.
if value is not None:
settings[key] = "{}".format(value)
if accepts_file:
# --file was introduced in Juju 1.23.2. Use it by default if
# available, since otherwise we'll break if the relation data is
# too big. Ideally we should tell relation-set to read the data from
# stdin, but that feature is broken in 1.23.2: Bug #1454678.
with tempfile.NamedTemporaryFile(delete=False) as settings_file:
settings_file.write(yaml.safe_dump(settings).encode("utf-8"))
subprocess.check_call(
relation_cmd_line + ["--file", settings_file.name])
os.remove(settings_file.name)
else:
for key, value in settings.items():
if value is None:
relation_cmd_line.append('{}='.format(key))
else:
relation_cmd_line.append('{}={}'.format(key, value))
subprocess.check_call(relation_cmd_line)
# Flush cache of any relation-gets for local unit
flush(local_unit())
def yaml(self, output):
"""Output data in YAML format"""
import yaml
yaml.safe_dump(output, self.outfile)
def save_errorlog(errorlog):
with open('out/errors.yml', 'w') as outfile:
yaml.safe_dump(errorlog, outfile, default_flow_style=False)
def append_config(file_name, p_domain, u_domain):
""" Append values into a yaml file """
with open(file_name) as yfile:
doc = yaml.load(yfile)
doc['credentials']['abot-epc']['abot-epc']['project-domain-name'] = (
p_domain)
doc['credentials']['abot-epc']['abot-epc']['user-domain-name'] = (
u_domain)
with open(file_name, 'w') as yfile:
yaml.safe_dump(doc, yfile, default_flow_style=False)
def relation_set(relation_id=None, relation_settings=None, **kwargs):
"""Set relation information for the current unit"""
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--help"], universal_newlines=True)
if relation_id is not None:
relation_cmd_line.extend(('-r', relation_id))
settings = relation_settings.copy()
settings.update(kwargs)
for key, value in settings.items():
# Force value to be a string: it always should, but some call
# sites pass in things like dicts or numbers.
if value is not None:
settings[key] = "{}".format(value)
if accepts_file:
# --file was introduced in Juju 1.23.2. Use it by default if
# available, since otherwise we'll break if the relation data is
# too big. Ideally we should tell relation-set to read the data from
# stdin, but that feature is broken in 1.23.2: Bug #1454678.
with tempfile.NamedTemporaryFile(delete=False) as settings_file:
settings_file.write(yaml.safe_dump(settings).encode("utf-8"))
subprocess.check_call(
relation_cmd_line + ["--file", settings_file.name])
os.remove(settings_file.name)
else:
for key, value in settings.items():
if value is None:
relation_cmd_line.append('{}='.format(key))
else:
relation_cmd_line.append('{}={}'.format(key, value))
subprocess.check_call(relation_cmd_line)
# Flush cache of any relation-gets for local unit
flush(local_unit())
def yaml(self, output):
"""Output data in YAML format"""
import yaml
yaml.safe_dump(output, self.outfile)
def relation_set(relation_id=None, relation_settings=None, **kwargs):
"""Set relation information for the current unit"""
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--help"], universal_newlines=True)
if relation_id is not None:
relation_cmd_line.extend(('-r', relation_id))
settings = relation_settings.copy()
settings.update(kwargs)
for key, value in settings.items():
# Force value to be a string: it always should, but some call
# sites pass in things like dicts or numbers.
if value is not None:
settings[key] = "{}".format(value)
if accepts_file:
# --file was introduced in Juju 1.23.2. Use it by default if
# available, since otherwise we'll break if the relation data is
# too big. Ideally we should tell relation-set to read the data from
# stdin, but that feature is broken in 1.23.2: Bug #1454678.
with tempfile.NamedTemporaryFile(delete=False) as settings_file:
settings_file.write(yaml.safe_dump(settings).encode("utf-8"))
subprocess.check_call(
relation_cmd_line + ["--file", settings_file.name])
os.remove(settings_file.name)
else:
for key, value in settings.items():
if value is None:
relation_cmd_line.append('{}='.format(key))
else:
relation_cmd_line.append('{}={}'.format(key, value))
subprocess.check_call(relation_cmd_line)
# Flush cache of any relation-gets for local unit
flush(local_unit())
def yaml(self, output):
"""Output data in YAML format"""
import yaml
yaml.safe_dump(output, self.outfile)