INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Prepare the session after the connection has been established. | def session_preparation(self):
"""Prepare the session after the connection has been established."""
self._test_channel_read()
self.set_base_prompt()
self.tmsh_mode()
self.set_base_prompt()
self.disable_paging(
command="modify cli preference pager disabled disp... |
tmsh command is equivalent to config command on F5. | def tmsh_mode(self, delay_factor=1):
"""tmsh command is equivalent to config command on F5."""
delay_factor = self.select_delay_factor(delay_factor)
self.clear_buffer()
command = "{}tmsh{}".format(self.RETURN, self.RETURN)
self.write_channel(command)
time.sleep(1 * delay_... |
Determine base prompt. | def set_base_prompt(
self, pri_prompt_terminator="$", alt_prompt_terminator="#", delay_factor=1
):
"""Determine base prompt."""
return super(LinuxSSH, self).set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
... |
Can t exit from root ( if root ) | def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs):
"""Can't exit from root (if root)"""
if self.username == "root":
exit_config_mode = False
return super(LinuxSSH, self).send_config_set(
config_commands=config_commands, exit_config_mode=exit... |
Exit enable mode. | def exit_enable_mode(self, exit_command="exit"):
"""Exit enable mode."""
delay_factor = self.select_delay_factor(delay_factor=0)
output = ""
if self.check_enable_mode():
self.write_channel(self.normalize_cmd(exit_command))
time.sleep(0.3 * delay_factor)
... |
Attempt to become root. | def enable(self, cmd="sudo su", pattern="ssword", re_flags=re.IGNORECASE):
"""Attempt to become root."""
delay_factor = self.select_delay_factor(delay_factor=0)
output = ""
if not self.check_enable_mode():
self.write_channel(self.normalize_cmd(cmd))
time.sleep(0.3... |
Get the file size of the remote file. | def remote_file_size(self, remote_cmd="", remote_file=None):
"""Get the file size of the remote file."""
return self._remote_file_size_unix(
remote_cmd=remote_cmd, remote_file=remote_file
) |
Use Secure Copy or Inline ( IOS - only ) to transfer files to/ from network devices. | def file_transfer(
ssh_conn,
source_file,
dest_file,
file_system=None,
direction="put",
disable_md5=False,
inline_transfer=False,
overwrite_file=False,
):
"""Use Secure Copy or Inline (IOS-only) to transfer files to/from network devices.
inline_transfer ONLY SUPPORTS TEXT FILES ... |
Remove the > when navigating into the different config level. | def set_base_prompt(self, *args, **kwargs):
"""Remove the > when navigating into the different config level."""
cur_base_prompt = super(AlcatelSrosSSH, self).set_base_prompt(*args, **kwargs)
match = re.search(r"(.*)(>.*)*#", cur_base_prompt)
if match:
# strip off >... from ba... |
Enter enable mode. | def enable(self, cmd="enable-admin", pattern="ssword", re_flags=re.IGNORECASE):
"""Enter enable mode."""
return super(AlcatelSrosSSH, self).enable(
cmd=cmd, pattern=pattern, re_flags=re_flags
) |
Check whether we are in enable - admin mode. SROS requires us to do this: * A: HOSTNAME# enable - admin MINOR: CLI Already in admin mode. * A: HOSTNAME# * A: HOSTNAME# enable - admin Password: MINOR: CLI Invalid password. * A: HOSTNAME# | def check_enable_mode(self, check_string="CLI Already in admin mode"):
"""Check whether we are in enable-admin mode.
SROS requires us to do this:
*A:HOSTNAME# enable-admin
MINOR: CLI Already in admin mode.
*A:HOSTNAME#
*A:HOSTNAME# enable-admin
Password:
... |
Enter into configuration mode on SROS device. | def config_mode(self, config_command="configure", pattern="#"):
""" Enter into configuration mode on SROS device."""
return super(AlcatelSrosSSH, self).config_mode(
config_command=config_command, pattern=pattern
) |
Exit from configuration mode. | def exit_config_mode(self, exit_config="exit all", pattern="#"):
""" Exit from configuration mode."""
return super(AlcatelSrosSSH, self).exit_config_mode(
exit_config=exit_config, pattern=pattern
) |
Checks if the device is in configuration mode or not. | def check_config_mode(self, check_string="config", pattern="#"):
""" Checks if the device is in configuration mode or not. """
return super(AlcatelSrosSSH, self).check_config_mode(
check_string=check_string, pattern=pattern
) |
Saves Config | def save_config(
self,
cmd="copy running-configuration startup-configuration",
confirm=False,
confirm_response="",
):
"""Saves Config"""
return super(DellDNOS6Base, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) |
Extreme attaches an id to the prompt. The id increases with every command. It needs to br stripped off to match the prompt. Eg. | def set_base_prompt(self, *args, **kwargs):
"""
Extreme attaches an id to the prompt. The id increases with every command.
It needs to br stripped off to match the prompt. Eg.
testhost.1 #
testhost.2 #
testhost.3 #
If new config is loaded and not sav... |
Extreme needs special handler here due to the prompt changes. | def send_command(self, *args, **kwargs):
"""Extreme needs special handler here due to the prompt changes."""
# Change send_command behavior to use self.base_prompt
kwargs.setdefault("auto_find_prompt", False)
# refresh self.base_prompt
self.set_base_prompt()
return supe... |
Saves configuration. | def save_config(
self, cmd="save configuration primary", confirm=False, confirm_response=""
):
"""Saves configuration."""
return super(ExtremeExosBase, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) |
Check if at shell prompt root | def enter_cli_mode(self):
"""Check if at shell prompt root@ and go into CLI."""
delay_factor = self.select_delay_factor(delay_factor=0)
count = 0
cur_prompt = ""
while count < 50:
self.write_channel(self.RETURN)
time.sleep(0.1 * delay_factor)
c... |
Strip the trailing router prompt from the output. | def strip_prompt(self, *args, **kwargs):
"""Strip the trailing router prompt from the output."""
a_string = super(JuniperBase, self).strip_prompt(*args, **kwargs)
return self.strip_context_items(a_string) |
Strip Juniper - specific output. | def strip_context_items(self, a_string):
"""Strip Juniper-specific output.
Juniper will also put a configuration context:
[edit]
and various chassis contexts:
{master:0}, {backup:1}
This method removes those lines.
"""
strings_to_strip = [
r... |
Checks if the device is in configuration mode or not. | def check_config_mode(self, check_string=")#", pattern=""):
"""
Checks if the device is in configuration mode or not.
Arista, unfortunately, does this:
loc1-core01(s1)#
Can also be (s2)
"""
log.debug("pattern: {0}".format(pattern))
self.write_channel(sel... |
Prepare the session after the connection has been established. | def session_preparation(self):
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging()
# Clear the read buffer
time.sleep(0.3 * self.gl... |
Convert \ r \ n or \ r \ r \ n to \ n and remove extra \ r s in the text. | def normalize_linefeeds(self, a_string):
"""Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text."""
newline = re.compile(r"(\r\r\n|\r\n)")
# NX-OS fix for incorrect MD5 on 9K (due to strange <enter> patterns on NX-OS)
return newline.sub(self.RESPONSE_RETURN, a_string).r... |
Checks if the device is in configuration mode or not. | def check_config_mode(self, check_string=")#", pattern="#"):
"""Checks if the device is in configuration mode or not."""
return super(CiscoNxosSSH, self).check_config_mode(
check_string=check_string, pattern=pattern
) |
Check if the dest_file already exists on the file system ( return boolean ). | def check_file_exists(self, remote_cmd=""):
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direction == "put":
if not remote_cmd:
remote_cmd = "dir {}{}".format(self.file_system, self.dest_file)
remote_out = self.ssh_ctl_c... |
Strip the trailing router prompt from the output. | def strip_prompt(self, a_string):
"""Strip the trailing router prompt from the output."""
expect_string = r"^(OK|ERROR|Command not recognized\.)$"
response_list = a_string.split(self.RESPONSE_RETURN)
last_line = response_list[-1]
if re.search(expect_string, last_line):
... |
Send command to network device retrieve output until router_prompt or expect_string | def send_command(self, *args, **kwargs):
"""
Send command to network device retrieve output until router_prompt or expect_string
By default this method will keep waiting to receive data until the network device prompt is
detected. The current network device prompt will be determined aut... |
Save Config for Extreme VDX. | def save_config(
self,
cmd="copy running-config startup-config",
confirm=True,
confirm_response="y",
):
"""Save Config for Extreme VDX."""
return super(ExtremeNosSSH, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) |
Exit configuration mode. | def exit_config_mode(self, exit_config="return", pattern=r">"):
"""Exit configuration mode."""
return super(HuaweiBase, self).exit_config_mode(
exit_config=exit_config, pattern=pattern
) |
Sets self. base_prompt | def set_base_prompt(
self, pri_prompt_terminator=">", alt_prompt_terminator="]", delay_factor=1
):
"""
Sets self.base_prompt
Used as delimiter for stripping of trailing prompt in output.
Should be set to something that is general and applies in multiple contexts. For Comwar... |
Save Config for HuaweiSSH | def save_config(self, cmd="save", confirm=False, confirm_response=""):
""" Save Config for HuaweiSSH"""
return super(HuaweiBase, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) |
Telnet login for Huawei Devices | def telnet_login(
self,
pri_prompt_terminator=r"]\s*$",
alt_prompt_terminator=r">\s*$",
username_pattern=r"(?:user:|username|login|user name)",
pwd_pattern=r"assword",
delay_factor=1,
max_loops=20,
):
"""Telnet login for Huawei Devices"""
dela... |
Commit the candidate configuration. | def commit(self, comment="", delay_factor=1):
"""
Commit the candidate configuration.
Commit the entered configuration. Raise an error and return the failure
if the commit fails.
default:
command_string = commit
comment:
command_string = commit com... |
Enable/ disable SCP on Cisco ASA. | def asa_scp_handler(ssh_conn, cmd="ssh scopy enable", mode="enable"):
"""Enable/disable SCP on Cisco ASA."""
if mode == "disable":
cmd = "no " + cmd
return ssh_conn.send_config_set([cmd]) |
Script to upgrade a Cisco ASA. | def main():
"""Script to upgrade a Cisco ASA."""
try:
ip_addr = raw_input("Enter ASA IP address: ")
except NameError:
ip_addr = input("Enter ASA IP address: ")
my_pass = getpass()
start_time = datetime.now()
print(">>>> {}".format(start_time))
net_device = {
"device_... |
Execute show version command using Netmiko. | def show_version(a_device):
"""Execute show version command using Netmiko."""
remote_conn = ConnectHandler(**a_device)
print()
print("#" * 80)
print(remote_conn.send_command("show version"))
print("#" * 80)
print() |
Use processes and Netmiko to connect to each of the devices. Execute show version on each device. Record the amount of time required to do this. | def main():
"""
Use processes and Netmiko to connect to each of the devices. Execute
'show version' on each device. Record the amount of time required to do this.
"""
start_time = datetime.now()
procs = []
for a_device in devices:
my_proc = Process(target=show_version, args=(a_devic... |
WLC presents with the following on login ( in certain OS versions ) | def special_login_handler(self, delay_factor=1):
"""WLC presents with the following on login (in certain OS versions)
login as: user
(Cisco Controller)
User: user
Password:****
"""
delay_factor = self.select_delay_factor(delay_factor)
i = 0
tim... |
For show run - config Cisco WLC adds a Press Enter to continue... message Even though pagination is disabled show run - config also has excessive delays in the output which requires special handling. Arguments are the same as send_command_timing () method | def send_command_w_enter(self, *args, **kwargs):
"""
For 'show run-config' Cisco WLC adds a 'Press Enter to continue...' message
Even though pagination is disabled
show run-config also has excessive delays in the output which requires special
handling.
Arguments are the s... |
Checks if the device is in configuration mode or not. | def check_config_mode(self, check_string="config", pattern=""):
"""Checks if the device is in configuration mode or not."""
if not pattern:
pattern = re.escape(self.base_prompt)
return super(CiscoWlcSSH, self).check_config_mode(check_string, pattern) |
Exit config_mode. | def exit_config_mode(self, exit_config="exit", pattern=""):
"""Exit config_mode."""
if not pattern:
pattern = re.escape(self.base_prompt)
return super(CiscoWlcSSH, self).exit_config_mode(exit_config, pattern) |
Saves Config. | def save_config(self, cmd="save config", confirm=True, confirm_response="y"):
"""Saves Config."""
self.enable()
if confirm:
output = self.send_command_timing(command_string=cmd)
if confirm_response:
output += self.send_command_timing(confirm_response)
... |
Recreate the key index. | def _BuildIndex(self):
"""Recreate the key index."""
self._index = {}
for i, k in enumerate(self._keys):
self._index[k] = i |
Get an item from the Row by column name. | def get(self, column, default_value=None):
"""Get an item from the Row by column name.
Args:
column: Tuple of column names, or a (str) column name, or positional
column number, 0-indexed.
default_value: The value to use if the key is not found.
Returns:
A list or string with ... |
Fetches the column number ( 0 indexed ). | def index(self, column): # pylint: disable=C6409
"""Fetches the column number (0 indexed).
Args:
column: A string, column to fetch the index of.
Returns:
An int, the row index number.
Raises:
ValueError: The specified column was not found.
"""
for i, key in enumerat... |
Sets row s colour attributes to a list of values in terminal. SGR. | def _SetColour(self, value_list):
"""Sets row's colour attributes to a list of values in terminal.SGR."""
if value_list is None:
self._color = None
return
colors = []
for color in value_list:
if color in terminal.SGR:
colors.append(colo... |
Inserts new values at a specified offset. | def Insert(self, key, value, row_index):
"""Inserts new values at a specified offset.
Args:
key: string for header value.
value: string for a data value.
row_index: Offset into row for data.
Raises:
IndexError: If the offset is out of bands.
"""
if row_index < 0:
... |
Applies the function to every row in the table. | def Map(self, function):
"""Applies the function to every row in the table.
Args:
function: A function applied to each row.
Returns:
A new TextTable()
Raises:
TableError: When transform is not invalid row entry. The transform
must be compatible with Append().
... |
Sorts rows in the texttable. | def sort(self, cmp=None, key=None, reverse=False):
"""Sorts rows in the texttable.
Args:
cmp: func, non default sort algorithm to use.
key: func, applied to each element before sorting.
reverse: bool, reverse order of sort.
"""
def _DefaultKey(value):
"""Default k... |
Extends all rows in the texttable. | def extend(self, table, keys=None):
"""Extends all rows in the texttable.
The rows are extended with the new columns from the table.
Args:
table: A texttable, the table to extend this table by.
keys: A set, the set of columns to use as the key. If None, the
row index is used.
... |
Removes a row from the table. | def Remove(self, row):
"""Removes a row from the table.
Args:
row: int, the row number to delete. Must be >= 1, as the header
cannot be removed.
Raises:
TableError: Attempt to remove nonexistent or header row.
"""
if row == 0 or row > self.size:
raise TableE... |
Returns the current row as a tuple. | def _GetRow(self, columns=None):
"""Returns the current row as a tuple."""
row = self._table[self._row_index]
if columns:
result = []
for col in columns:
if col not in self.header:
raise TableError("Column header %s not known in table.... |
Sets the current row to new list. | def _SetRow(self, new_values, row=0):
"""Sets the current row to new list.
Args:
new_values: List|dict of new values to insert into row.
row: int, Row to insert values into.
Raises:
TableError: If number of new values is not equal to row size.
"""
if not row:
... |
Sets header of table to the given tuple. | def _SetHeader(self, new_values):
"""Sets header of table to the given tuple.
Args:
new_values: Tuple of new header values.
"""
row = self.row_class()
row.row = 0
for v in new_values:
row[v] = v
self._table[0] = row |
Finds the largest indivisible word of a string. | def _SmallestColSize(self, text):
"""Finds the largest indivisible word of a string.
...and thus the smallest possible column width that can contain that
word unsplit over rows.
Args:
text: A string of text potentially consisting of words.
Returns:
Integer size of the largest sing... |
Retrieves the first non header row with the column of the given value. | def RowWith(self, column, value):
"""Retrieves the first non header row with the column of the given value.
Args:
column: str, the name of the column to check.
value: str, The value of the column to check.
Returns:
A Row() of the first row found, None otherwise.
Raises:
In... |
Appends a new column to the table. | def AddColumn(self, column, default="", col_index=-1):
"""Appends a new column to the table.
Args:
column: A string, name of the column to add.
default: Default value for entries. Defaults to ''.
col_index: Integer index for where to insert new column.
Raises:
TableError: Colum... |
Adds a new row ( list ) to the table. | def Append(self, new_values):
"""Adds a new row (list) to the table.
Args:
new_values: Tuple, dict, or Row() of new values to append as a row.
Raises:
TableError: Supplied tuple not equal to table width.
"""
newrow = self.NewRow()
newrow.values = new_values
self... |
Fetches a new empty row with headers populated. | def NewRow(self, value=""):
"""Fetches a new, empty row, with headers populated.
Args:
value: Initial value to set each row entry to.
Returns:
A Row() object.
"""
newrow = self.row_class()
newrow.row = self.size + 1
newrow.table = self
headers = self._He... |
Parses buffer into tabular format. | def CsvToTable(self, buf, header=True, separator=","):
"""Parses buffer into tabular format.
Strips off comments (preceded by '#').
Optionally parses and indexes by first line (header).
Args:
buf: String file buffer containing CSV data.
header: Is the first line of buffer a header.
... |
Save Config | def save_config(self, cmd="save config", confirm=False, confirm_response=""):
"""Save Config"""
return super(ExtremeVspSSH, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) |
Make sure paging is disabled. | def disable_paging(self, command="pager off", delay_factor=1):
"""Make sure paging is disabled."""
return super(PluribusSSH, self).disable_paging(
command=command, delay_factor=delay_factor
) |
Read YAML file. | def load_yaml_file(yaml_file):
"""Read YAML file."""
try:
import yaml
except ImportError:
sys.exit("Unable to import yaml module.")
try:
with io.open(yaml_file, "rt", encoding="utf-8") as fname:
return yaml.safe_load(fname)
except IOError:
sys.exit("Unable... |
Look for. netmiko. yml in current dir then ~/. netmiko. yml. | def find_cfg_file(file_name=None):
"""Look for .netmiko.yml in current dir, then ~/.netmiko.yml."""
base_file = ".netmiko.yml"
check_files = [base_file, os.path.expanduser("~") + "/" + base_file]
if file_name:
check_files.insert(0, file_name)
for test_file in check_files:
if os.path.... |
Print out inventory devices and groups. | def display_inventory(my_devices):
"""Print out inventory devices and groups."""
inventory_groups = ["all"]
inventory_devices = []
for k, v in my_devices.items():
if isinstance(v, list):
inventory_groups.append(k)
elif isinstance(v, dict):
inventory_devices.append... |
Dynamically create all group. | def obtain_all_devices(my_devices):
"""Dynamically create 'all' group."""
new_devices = {}
for device_name, device_or_group in my_devices.items():
# Skip any groups
if not isinstance(device_or_group, list):
new_devices[device_name] = device_or_group
return new_devices |
Ensure directory exists. Create if necessary. | def ensure_dir_exists(verify_dir):
"""Ensure directory exists. Create if necessary."""
if not os.path.exists(verify_dir):
# Doesn't exist create dir
os.makedirs(verify_dir)
else:
# Exists
if not os.path.isdir(verify_dir):
# Not a dir, raise an exception
... |
Check environment first then default dir | def find_netmiko_dir():
"""Check environment first, then default dir"""
try:
netmiko_base_dir = os.environ["NETMIKO_DIR"]
except KeyError:
netmiko_base_dir = NETMIKO_BASE_DIR
netmiko_base_dir = os.path.expanduser(netmiko_base_dir)
if netmiko_base_dir == "/":
raise ValueError(... |
Write Python2 and Python3 compatible byte stream. | def write_bytes(out_data, encoding="ascii"):
"""Write Python2 and Python3 compatible byte stream."""
if sys.version_info[0] >= 3:
if isinstance(out_data, type("")):
if encoding == "utf-8":
return out_data.encode("utf-8")
else:
return out_data.encod... |
returns valid COM Port. | def check_serial_port(name):
"""returns valid COM Port."""
try:
cdc = next(serial.tools.list_ports.grep(name))
return cdc[0]
except StopIteration:
msg = "device {} not found. ".format(name)
msg += "available devices are: "
ports = list(serial.tools.list_ports.comports... |
Find and return the ntc - templates/ templates dir. | def get_template_dir():
"""Find and return the ntc-templates/templates dir."""
try:
template_dir = os.path.expanduser(os.environ["NET_TEXTFSM"])
index = os.path.join(template_dir, "index")
if not os.path.isfile(index):
# Assume only base ./ntc-templates specified
... |
Converts TextFSM cli_table object to list of dictionaries. | def clitable_to_dict(cli_table):
"""Converts TextFSM cli_table object to list of dictionaries."""
objs = []
for row in cli_table:
temp_dict = {}
for index, element in enumerate(row):
temp_dict[cli_table.header[index].lower()] = element
objs.append(temp_dict)
return ob... |
Convert raw CLI output to structured data using TextFSM template. | def get_structured_data(raw_output, platform, command):
"""Convert raw CLI output to structured data using TextFSM template."""
template_dir = get_template_dir()
index_file = os.path.join(template_dir, "index")
textfsm_obj = clitable.CliTable(index_file, template_dir)
attrs = {"Command": command, "P... |
Save Config | def save_config(self, cmd="write memory", confirm=False, confirm_response=""):
"""Save Config"""
return super(ExtremeNetironBase, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) |
Create a ElastiCache Redis Node and EC2 Instance | def main():
"""
Create a ElastiCache Redis Node and EC2 Instance
"""
template = Template()
# Description
template.add_description(
'AWS CloudFormation Sample Template ElastiCache_Redis:'
'Sample template showing how to create an Amazon'
'ElastiCache Redis Cluster. **WAR... |
DBInstance Iops validation rules. | def validate_iops(iops):
"""DBInstance Iops validation rules."""
iops = integer(iops)
if int(iops) == 0:
return iops
if int(iops) < 1000:
raise ValueError("DBInstance Iops, if set, must be greater than 1000.")
return iops |
Validate PreferredBackupWindow for DBInstance | def validate_backup_window(window):
"""Validate PreferredBackupWindow for DBInstance"""
hour = r'[01]?[0-9]|2[0-3]'
minute = r'[0-5][0-9]'
r = ("(?P<start_hour>%s):(?P<start_minute>%s)-"
"(?P<end_hour>%s):(?P<end_minute>%s)") % (hour, minute, hour, minute)
range_regex = re.compile(r)
m... |
Validate PreferredMaintenanceWindow for DBInstance | def validate_maintenance_window(window):
"""Validate PreferredMaintenanceWindow for DBInstance"""
days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
day_re = r'[A-Z]{1}[a-z]{2}'
hour = r'[01]?[0-9]|2[0-3]'
minute = r'[0-5][0-9]'
r = ("(?P<start_day>%s):(?P<start_hour>%s):(?P<start_minute>... |
Validate ScalingConfiguration capacity for serverless DBCluster | def validate_capacity(capacity):
"""Validate ScalingConfiguration capacity for serverless DBCluster"""
if capacity not in VALID_SCALING_CONFIGURATION_CAPACITIES:
raise ValueError(
"ScalingConfiguration capacity must be one of: {}".format(
", ".join(map(
s... |
Given a file name to a valid file returns the file object. | def file_contents(file_name):
"""Given a file name to a valid file returns the file object."""
curr_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(curr_dir, file_name)) as the_file:
contents = the_file.read()
return contents |
Handles using. title if the given object is a troposphere resource. | def depends_on_helper(obj):
""" Handles using .title if the given object is a troposphere resource.
If the given object is a troposphere resource, use the `.title` attribute
of that resource. If it's a string, just use the string. This should allow
more pythonic use of DependsOn.
"""
if isinsta... |
Sets the Label used in the User Interface for the given parameter.: type parameter: str or Parameter: type label: str | def set_parameter_label(self, parameter, label):
"""
Sets the Label used in the User Interface for the given parameter.
:type parameter: str or Parameter
:type label: str
"""
labels = self.metadata\
.setdefault("AWS::CloudFormation::Interface", {})\
... |
Add a parameter under a group ( created if needed ).: type parameter: str or Parameter: type group_name: str | def add_parameter_to_group(self, parameter, group_name):
"""
Add a parameter under a group (created if needed).
:type parameter: str or Parameter
:type group_name: str
"""
groups = self.metadata \
.setdefault("AWS::CloudFormation::Interface", {}) \
... |
Imports userdata from a file. | def from_file(filepath, delimiter='', blanklines=False):
"""Imports userdata from a file.
:type filepath: string
:param filepath The absolute path to the file.
:type delimiter: string
:param: delimiter Delimiter to use with the troposphere.Join().
:type blanklines: boolean
:param bla... |
Get the events in batches and return in chronological order | def get_events(conn, stackname):
"""Get the events in batches and return in chronological order"""
next = None
event_list = []
while 1:
events = conn.describe_stack_events(stackname, next)
event_list.append(events)
if events.next_token is None:
break
next = ev... |
Show and then tail the event log | def tail(conn, stack_name, log_func=_tail_print, sleep_time=5,
include_initial=True):
"""Show and then tail the event log"""
# First dump the full list of events in chronological order and keep
# track of the events we've seen already
seen = set()
initial_events = get_events(conn, stack_nam... |
Validate memory size for Lambda Function: param memory_value: The memory size specified in the Function: return: The provided memory size if it is valid | def validate_memory_size(memory_value):
""" Validate memory size for Lambda Function
:param memory_value: The memory size specified in the Function
:return: The provided memory size if it is valid
"""
memory_value = int(positive_integer(memory_value))
if memory_value not in MEMORY_VALUES:
... |
Return a list of validators specified in the override file | def get_validator_list(self):
"""Return a list of validators specified in the override file"""
ignore = [
'dict',
]
vlist = []
if not self.override:
return vlist
for k, v in list(self.override['classes'].items()):
if 'validator' in v:
... |
Look for a Tags object to output a Tags import | def _output_tags(self):
"""Look for a Tags object to output a Tags import"""
for class_name, properties in sorted(self.resources.items()):
for key, value in sorted(properties.items()):
validator = self.override.get_validator(class_name, key)
if key == 'Tags' a... |
Decode a properties type looking for a specific type. | def _check_type(self, check_type, properties):
"""Decode a properties type looking for a specific type."""
if 'PrimitiveType' in properties:
return properties['PrimitiveType'] == check_type
if properties['Type'] == 'List':
if 'ItemType' in properties:
retu... |
Walk the resources/ properties looking for a specific type. | def _walk_for_type(self, check_type):
"""Walk the resources/properties looking for a specific type."""
for class_name, properties in sorted(self.resources.items()):
for key, value in sorted(properties.items()):
if self._check_type(check_type, value):
retur... |
Return a list of non - primitive types used by this object. | def _get_type_list(self, props):
"""Return a list of non-primitive types used by this object."""
type_list = []
for k, v in list(props.items()):
t = self._get_property_type(v)
if t is not None:
type_list.append(t)
return sorted(type_list) |
Output common validator types based on usage. | def _output_validators(self):
"""Output common validator types based on usage."""
if self._walk_for_type('Boolean'):
print("from .validators import boolean")
if self._walk_for_type('Integer'):
print("from .validators import integer")
vlist = self.override.get_vali... |
Build a tree of non - primitive typed dependency order. | def build_tree(self, name, props, resource_name=None):
"""Build a tree of non-primitive typed dependency order."""
n = Node(name, props, resource_name)
prop_type_list = self._get_type_list(props)
if not prop_type_list:
return n
prop_type_list = sorted(prop_type_list)
... |
Given a dependency tree of objects output it in DFS order. | def output_tree(self, t, seen):
"""Given a dependency tree of objects, output it in DFS order."""
if not t:
return
for c in t.children:
self.output_tree(c, seen)
if t.name in seen:
return
seen[t.name] = True
if t.resource_name:
... |
Output the generated source file. | def output(self):
"""Output the generated source file."""
print(copyright_header % spec_version)
self._output_imports()
self._output_tags()
self._output_validators()
header = self.override.get_header()
if header:
print()
print()
... |
Returns the list of all troposphere members we are able to construct | def inspect_members(self):
"""
Returns the list of all troposphere members we are able to
construct
"""
if not self._inspect_members:
TemplateGenerator._inspect_members = \
self._import_all_troposphere_modules()
return self._inspect_members |
Returns a map of ResourceType: ResourceClass | def inspect_resources(self):
""" Returns a map of `ResourceType: ResourceClass` """
if not self._inspect_resources:
d = {}
for m in self.inspect_members:
if issubclass(m, (AWSObject, cloudformation.AWSCustomObject)) \
and hasattr(m, 'resour... |
Returns a map of FunctionName: FunctionClass | def inspect_functions(self):
""" Returns a map of `FunctionName: FunctionClass` """
if not self._inspect_functions:
d = {}
for m in self.inspect_members:
if issubclass(m, AWSHelperFn):
d[m.__name__] = m
TemplateGenerator._inspect_f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.