Issues (70)

ssg/ansible.py (1 issue)

1
"""
2
Common functions for processing Ansible in SSG
3
"""
4
5
from __future__ import absolute_import
6
from __future__ import print_function
7
8
import re
9
10
from .constants import ansible_version_requirement_pre_task_name
11
from .constants import min_ansible_version
12
from .constants import REF_PREFIX_MAP
13
14
15
def add_minimum_version(ansible_src):
16
    """
17
    Adds minimum ansible version to an Ansible script
18
    """
19
    pre_task = (""" - hosts: all
20
   pre_tasks:
21
     - name: %s
22
       assert:
23
         that: "ansible_version.full is version_compare('%s', '>=')"
24
         msg: >
25
           "You must update Ansible to at least version %s to use this role."
26
          """ % (ansible_version_requirement_pre_task_name,
27
                 min_ansible_version, min_ansible_version))
28
29
    if ' - hosts: all' not in ansible_src:
30
        return ansible_src
31
32
    if 'pre_task' in ansible_src:
33
        if 'ansible_version.full is version_compare' in ansible_src:
34
            return ansible_src
35
36
        raise ValueError(
37
            "A pre_task already exists in ansible_src; failing to process: %s" %
38
            ansible_src)
39
40
    return ansible_src.replace(" - hosts: all", pre_task, 1)
41
42
43
def add_play_name(ansible_src, profile):
44
    old_play_start = r"^( *)- hosts: all"
45
    new_play_start = (
46
        r"\1- name: Ansible Playbook for %s\n\1  hosts: all" % (profile))
47
    return re.sub(old_play_start, new_play_start, ansible_src, flags=re.M)
48
49
50
def remove_too_many_blank_lines(ansible_src):
51
    """
52
    Condenses three or more empty lines as two.
53
    """
54
    return re.sub(r'\n{4,}', '\n\n\n', ansible_src, 0, flags=re.M)
55
56
57
def remove_trailing_whitespace(ansible_src):
58
    """
59
    Removes trailing whitespace in an Ansible script
60
    """
61
    return re.sub(r'[ \t]+$', '', ansible_src, 0, flags=re.M)
62
63
64
def strip_eof(ansible_src):
65
    """
66
    Removes extra newlines at end of file
67
    """
68
    return ansible_src.rstrip() + "\n"
69
70
71
def _strings_to_list(one_or_more_strings):
72
    """
73
    Output a list, that either contains one string, or a list of strings.
74
    In Python, strings can be cast to lists without error, but with unexpected result.
75
    """
76
    if isinstance(one_or_more_strings, str):
77
        return [one_or_more_strings]
78
    else:
79
        return list(one_or_more_strings)
80
81
82 View Code Duplication
def update_yaml_list_or_string(current_contents, new_contents):
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
83
    result = []
84
    if current_contents:
85
        result += _strings_to_list(current_contents)
86
    if new_contents:
87
        result += _strings_to_list(new_contents)
88
    if not result:
89
        result = ""
90
    if len(result) == 1:
91
        result = result[0]
92
    return result
93