Skip to content

Commit 66b5d84

Browse files
authored
Merge pull request #12 from berttejeda/github/pypackage_missing_lib
Mistakenly ignored lib folder!
2 parents 96faffa + 28639ad commit 66b5d84

File tree

17 files changed

+869
-1
lines changed

17 files changed

+869
-1
lines changed

.gitignore

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ dist/
1717
downloads/
1818
eggs/
1919
.eggs/
20-
lib/
2120
lib64/
2221
parts/
2322
sdist/

ansible_taskrunner/lib/__init__.py

Whitespace-only changes.
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Imports
2+
import logging
3+
import sys
4+
5+
provider_name = 'bash'
6+
7+
# Logging
8+
logger = logging.getLogger('logger')
9+
logger.setLevel(logging.INFO)
10+
11+
# Import third-party and custom modules
12+
try:
13+
import click
14+
from .. import reindent
15+
from .. import YamlCLIInvocation
16+
except ImportError as e:
17+
print('Failed to import at least one required module')
18+
print('Error was %s' % e)
19+
print('Please install/update the required modules:')
20+
print('pip install -U -r requirements.txt')
21+
sys.exit(1)
22+
23+
24+
class ProviderCLI:
25+
def __init__(self, parameter_set=None, vars_input={}):
26+
self.vars = vars_input
27+
self.parameter_set = parameter_set
28+
self.logger = logger
29+
pass
30+
31+
@staticmethod
32+
def options(func):
33+
"""Add provider-specific click options"""
34+
return func
35+
36+
@staticmethod
37+
def invocation(yaml_input_file=None,
38+
string_vars=[],
39+
default_vars={},
40+
paramset_var=None,
41+
bash_functions=[],
42+
cli_vars='',
43+
yaml_vars={},
44+
list_vars=[],
45+
debug=False,
46+
args=None,
47+
prefix='',
48+
raw_args='',
49+
kwargs={}):
50+
"""Invoke commands according to provider"""
51+
logger.info('Bash Command Provider')
52+
command = '''
53+
{dsv}
54+
{psv}
55+
{dlv}
56+
{clv}
57+
{bfn}
58+
'''.format(
59+
dlv='\n'.join(list_vars),
60+
dsv='\n'.join(string_vars),
61+
psv=paramset_var,
62+
clv=cli_vars,
63+
bfn='\n'.join(bash_functions),
64+
deb=debug
65+
)
66+
command = reindent(command, 0)
67+
# Command invocation
68+
if prefix == 'echo':
69+
logger.info("ECHO MODE ON")
70+
print(command)
71+
else:
72+
YamlCLIInvocation().call(command)
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# Imports
2+
import logging
3+
import sys
4+
5+
# Logging
6+
logger = logging.getLogger('logger')
7+
logger.setLevel(logging.INFO)
8+
9+
# Import third-party and custom modules
10+
try:
11+
import click
12+
except ImportError as e:
13+
print('Failed to import at least one required module')
14+
print('Error was %s' % e)
15+
print('pip install -U -r requirements.txt')
16+
sys.exit(1)
17+
18+
19+
class ExtendedEpilog(click.Group):
20+
def format_epilog(self, ctx, formatter):
21+
"""Format click epilog to honor newline characters"""
22+
if self.epilog:
23+
formatter.write_paragraph()
24+
for line in self.epilog.split('\n'):
25+
formatter.write_text(line)
26+
27+
28+
class ExtendedHelp(click.Command):
29+
def format_help(self, ctx, formatter):
30+
"""Format click help to honor newline characters"""
31+
if self.help:
32+
formatter.write_paragraph()
33+
for line in self.help.split('\n'):
34+
formatter.write_text(line)
35+
opts = []
36+
for param in self.get_params(ctx):
37+
rv = param.get_help_record(ctx)
38+
if rv is not None:
39+
opts.append(rv)
40+
if opts:
41+
with formatter.section('Options'):
42+
formatter.write_dl(opts)
43+
if self.epilog:
44+
formatter.write_paragraph()
45+
for line in self.epilog.split('\n'):
46+
formatter.write_text(line)
47+
48+
49+
class ExtendCLI():
50+
def __init__(self, parameter_set=None, vars_input={}):
51+
self.vars = vars_input
52+
self.parameter_set = parameter_set
53+
self.logger = logger
54+
pass
55+
56+
def process_options(self, parameters, func, is_required=False):
57+
"""Read dictionary of parameters and translate to click options"""
58+
if not parameters:
59+
parameters = {}
60+
numargs = 1
61+
numargs_unlimited_is_set = False
62+
numargs_unlimited_count = 0
63+
numargs_unlimited_count_max = 1
64+
vanilla_parameters = dict(
65+
[(k, v) for k, v in parameters.items() if not isinstance(parameters[k], dict)])
66+
if self.parameter_set:
67+
_parameters = parameters.get(self.parameter_set, {})
68+
if _parameters:
69+
parameters = {}
70+
parameters.update(vanilla_parameters)
71+
parameters.update(_parameters)
72+
else:
73+
parameters = vanilla_parameters
74+
for cli_option, value in parameters.items():
75+
if isinstance(value, list):
76+
if len(value) == 1:
77+
numargs_unlimited_is_set = True
78+
numargs_unlimited_count += 1
79+
value = str(value[0])
80+
numargs = -1
81+
elif len(value) > 1:
82+
numargs = value[1]
83+
value = str(value[0])
84+
option_help = value
85+
if '|' in cli_option:
86+
option_string = cli_option.split('|')
87+
first_option = option_string[0].strip()
88+
second_option = option_string[1].strip()
89+
numargs = 1 if numargs < 1 else numargs
90+
option = click.option(first_option, second_option, value, type=str,
91+
nargs=numargs, help=option_help, required=is_required)
92+
else:
93+
if numargs_unlimited_is_set and not numargs_unlimited_count > numargs_unlimited_count_max:
94+
option = click.argument(
95+
cli_option, nargs=numargs, required=is_required)
96+
else:
97+
numargs = 1 if numargs < 1 else numargs
98+
option = click.option(
99+
cli_option, value, is_flag=True, default=False, help=option_help, required=is_required)
100+
func = option(func)
101+
numargs_unlimited_is_set = False
102+
numargs = 1
103+
return func
104+
105+
def options(self, func):
106+
"""Read dictionary of parameters, append these as additional options to incoming click function"""
107+
required_parameters = self.vars.get('required_parameters', {})
108+
extended_cli_func_required = self.process_options(
109+
required_parameters, func, is_required=True)
110+
optional_parameters = self.vars.get('optional_parameters', {})
111+
extended_cli_func = self.process_options(
112+
optional_parameters, extended_cli_func_required)
113+
# if required_parameters:
114+
# self.logger.warning("The value for 'required_parameters' is invalid")
115+
return extended_cli_func
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
ERR_ARGS_TASKF_OVERRIDE = '''
2+
When specifying a task file override, you must do so like this:
3+
{script} -f /path/to/mytasks.yaml
4+
{script} --tasks-file /path/to/mytasks.yaml
5+
Additionally, only task file overrides ending in .yml or .yaml are accepted
6+
'''
7+
8+
# see https://stackoverflow.com/questions/6234405/logging-uncaught-exceptions-in-python
9+
10+
11+
def catchException(logger, script_name, typ, value, traceback):
12+
"""Log uncaught exception to python logger"""
13+
logger.critical("Program Crash")
14+
logger.critical("Type: %s" % typ)
15+
logger.critical("Value: %s" % value)
16+
logger.critical("Traceback: %s" % traceback)
17+
logger.info(
18+
"Run same command but with %s --debug to see full stack trace!" % script_name)
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Defaults
2+
ansi_colors = """
3+
RESTORE=$(echo -en '\033[0m')
4+
RED=$(echo -en '\033[00;31m')
5+
GREEN=$(echo -en '\033[00;32m')
6+
YELLOW=$(echo -en '\033[00;33m')
7+
BLUE=$(echo -en '\033[00;34m')
8+
MAGENTA=$(echo -en '\033[00;35m')
9+
PURPLE=$(echo -en '\033[00;35m')
10+
CYAN=$(echo -en '\033[00;36m')
11+
LIGHTGRAY=$(echo -en '\033[00;37m')
12+
"""
13+
14+
logging_format = "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s"
15+
16+
17+
def reindent(s, numSpaces):
18+
"""Remove leading spaces from string see: Python Cookbook by David Ascher, Alex Martelli"""
19+
s = s.split('\n')
20+
s = [(numSpaces * ' ') + line.lstrip() for line in s]
21+
s = '\n'.join(s)
22+
return s
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
SAMPLE_CONFIG = '''
2+
---
3+
cli:
4+
providers:
5+
default: ansible
6+
...
7+
'''
8+
9+
SAMPLE_TASKS_MANIFEST = '''
10+
- hosts: myhosts
11+
gather_facts: true
12+
become: true
13+
vars:
14+
myvar1: myvalue1
15+
myvar2: myvalue2
16+
myvar3: myvalue3
17+
myvar4: |
18+
This is a multiline value
19+
of type string
20+
myvar5:
21+
- mylistvalue1
22+
- mylistvalue2
23+
- mylistvalue3
24+
- mylistvalue4
25+
required_parameters:
26+
aws:
27+
-d|--db-hosts: dbhosts_aws
28+
-a|--some-special-aws-flag: aws_flag
29+
gcp:
30+
-d|--db-hosts: dbhosts_gcp
31+
-g|--some-special-gcp-flag: gcp_flag
32+
-d|--db-hosts: dbhosts
33+
-w|--web-hosts: webhosts
34+
-t|--some-parameter: some_value
35+
optional_parameters:
36+
-l|--another-parameter: another_value
37+
-A: hello
38+
-PR: preflight_and_run
39+
--debug-mode: debug_mode
40+
help:
41+
message: |
42+
Do something against db and web hosts
43+
epilog: |
44+
This line will be displayed at the end of the help text readme
45+
examples:
46+
- example1: |
47+
Usage example 1
48+
- example2: |
49+
Usage example 2
50+
inventory: |
51+
[web-hosts]
52+
$(echo ${webhosts} | tr ',' '\\n')
53+
[db-hosts]
54+
$(echo ${dbhosts} | tr ',' '\\n')
55+
[myhosts:children]
56+
deployment-hosts
57+
web-hosts
58+
db-hosts
59+
functions:
60+
hello:
61+
shell: bash
62+
source: |-
63+
echo hello
64+
preflight_and_run:
65+
shell: bash
66+
source: |-
67+
echo 'Running Preflight Tasks!'
68+
tasks run -d dbhost1 -w webhost1 -t value1
69+
tasks:
70+
- debug:
71+
msg: |
72+
Hello from Ansible!
73+
You specified: {{ some_value }}
74+
You specified: {{ another_value }}
75+
'''
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Import builtins
2+
import os
3+
import sys
4+
5+
# Import third-party and custom modules
6+
try:
7+
from superduperconfig import SuperDuperConfig
8+
except ImportError as e:
9+
print('Failed to import at least one required module')
10+
print('Error was %s' % e)
11+
print('Please install/update the required modules:')
12+
print('pip install -U -r requirements.txt')
13+
sys.exit(1)
14+
15+
16+
def get_strings():
17+
self_path = os.path.dirname(os.path.abspath(__file__))
18+
__program_name__ = 'tasks'
19+
superconf = SuperDuperConfig(__program_name__)
20+
language_file = '%s/en.yaml' % self_path
21+
return superconf.load_config(language_file)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
strings:
2+
info:

ansible_taskrunner/lib/providers/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)