| 1 |
# (c) 2013, Jayson Vantuyl <[email protected]> |
| 2 |
# (c) 2012-17 Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
DOCUMENTATION = """ |
| 7 |
name: sequence |
| 8 |
author: Jayson Vantuyl (!UNKNOWN) <[email protected]> |
| 9 |
version_added: "1.0" |
| 10 |
short_description: generate a list based on a number sequence |
| 11 |
description: |
| 12 |
- generates a sequence of items. You can specify a start value, an end value, an optional "stride" value that specifies the number of steps |
| 13 |
to increment the sequence, and an optional printf-style format string. |
| 14 |
- 'Arguments can be specified as key=value pair strings or as a shortcut form of the arguments string is also accepted: [start-]end[/stride][:format].' |
| 15 |
- 'Numerical values can be specified in decimal, hexadecimal (0x3f8) or octal (0600).' |
| 16 |
- Starting at version 1.9.2, negative strides are allowed. |
| 17 |
- Generated items are strings. Use Jinja2 filters to convert items to preferred type, e.g. C({{ 1 + item|int }}). |
| 18 |
- See also Jinja2 C(range) filter as an alternative. |
| 19 |
options: |
| 20 |
start: |
| 21 |
description: number at which to start the sequence |
| 22 |
default: 1 |
| 23 |
type: integer |
| 24 |
end: |
| 25 |
description: number at which to end the sequence, dont use this with count |
| 26 |
type: integer |
| 27 |
count: |
| 28 |
description: number of elements in the sequence, this is not to be used with end |
| 29 |
type: integer |
| 30 |
stride: |
| 31 |
description: increments between sequence numbers, the default is 1 unless the end is less than the start, then it is -1. |
| 32 |
type: integer |
| 33 |
default: 1 |
| 34 |
format: |
| 35 |
description: return a string with the generated number formatted in |
| 36 |
default: "%d" |
| 37 |
""" |
| 38 |
|
| 39 |
EXAMPLES = """ |
| 40 |
- name: create some test users |
| 41 |
ansible.builtin.user: |
| 42 |
name: "{{ item }}" |
| 43 |
state: present |
| 44 |
groups: "evens" |
| 45 |
with_sequence: start=0 end=32 format=testuser%02x |
| 46 |
|
| 47 |
- name: create a series of directories with even numbers for some reason |
| 48 |
ansible.builtin.file: |
| 49 |
dest: "/var/stuff/{{ item }}" |
| 50 |
state: directory |
| 51 |
with_sequence: start=4 end=16 stride=2 |
| 52 |
|
| 53 |
- name: a simpler way to use the sequence plugin create 4 groups |
| 54 |
ansible.builtin.group: |
| 55 |
name: "group{{ item }}" |
| 56 |
state: present |
| 57 |
with_sequence: count=4 |
| 58 |
|
| 59 |
- name: the final countdown |
| 60 |
ansible.builtin.debug: |
| 61 |
msg: "{{item}} seconds to detonation" |
| 62 |
with_sequence: start=10 end=0 stride=-1 |
| 63 |
|
| 64 |
- name: Use of variable |
| 65 |
ansible.builtin.debug: |
| 66 |
msg: "{{ item }}" |
| 67 |
with_sequence: start=1 end="{{ end_at }}" |
| 68 |
vars: |
| 69 |
- end_at: 10 |
| 70 |
""" |
| 71 |
|
| 72 |
RETURN = """ |
| 73 |
_list: |
| 74 |
description: |
| 75 |
- A list containing generated sequence of items |
| 76 |
type: list |
| 77 |
elements: str |
| 78 |
""" |
| 79 |
|
| 80 |
from re import compile as re_compile, IGNORECASE |
| 81 |
|
| 82 |
from ansible.errors import AnsibleError |
| 83 |
from ansible.parsing.splitter import parse_kv |
| 84 |
from ansible.plugins.lookup import LookupBase |
| 85 |
|
| 86 |
|
| 87 |
# shortcut format |
| 88 |
NUM = "(0?x?[0-9a-f]+)" |
| 89 |
SHORTCUT = re_compile( |
| 90 |
"^(" + # Group 0 |
| 91 |
NUM + # Group 1: Start |
| 92 |
"-)?" + |
| 93 |
NUM + # Group 2: End |
| 94 |
"(/" + # Group 3 |
| 95 |
NUM + # Group 4: Stride |
| 96 |
")?" + |
| 97 |
"(:(.+))?$", # Group 5, Group 6: Format String |
| 98 |
IGNORECASE |
| 99 |
) |
| 100 |
FIELDS = frozenset(('start', 'end', 'stride', 'count', 'format')) |
| 101 |
|
| 102 |
|
| 103 |
class LookupModule(LookupBase): |
| 104 |
""" |
| 105 |
sequence lookup module |
| 106 |
|
| 107 |
Used to generate some sequence of items. Takes arguments in two forms. |
| 108 |
|
| 109 |
The simple / shortcut form is: |
| 110 |
|
| 111 |
[start-]end[/stride][:format] |
| 112 |
|
| 113 |
As indicated by the brackets: start, stride, and format string are all |
| 114 |
optional. The format string is in the style of printf. This can be used |
| 115 |
to pad with zeros, format in hexadecimal, etc. All of the numerical values |
| 116 |
can be specified in octal (i.e. 0664) or hexadecimal (i.e. 0x3f8). |
| 117 |
Negative numbers are not supported. |
| 118 |
|
| 119 |
Some examples: |
| 120 |
|
| 121 |
5 -> ["1","2","3","4","5"] |
| 122 |
5-8 -> ["5", "6", "7", "8"] |
| 123 |
2-10/2 -> ["2", "4", "6", "8", "10"] |
| 124 |
4:host%02d -> ["host01","host02","host03","host04"] |
| 125 |
|
| 126 |
The standard Ansible key-value form is accepted as well. For example: |
| 127 |
|
| 128 |
start=5 end=11 stride=2 format=0x%02x -> ["0x05","0x07","0x09","0x0a"] |
| 129 |
|
| 130 |
This format takes an alternate form of "end" called "count", which counts |
| 131 |
some number from the starting value. For example: |
| 132 |
|
| 133 |
count=5 -> ["1", "2", "3", "4", "5"] |
| 134 |
start=0x0f00 count=4 format=%04x -> ["0f00", "0f01", "0f02", "0f03"] |
| 135 |
start=0 count=5 stride=2 -> ["0", "2", "4", "6", "8"] |
| 136 |
start=1 count=5 stride=2 -> ["1", "3", "5", "7", "9"] |
| 137 |
|
| 138 |
The count option is mostly useful for avoiding off-by-one errors and errors |
| 139 |
calculating the number of entries in a sequence when a stride is specified. |
| 140 |
""" |
| 141 |
|
| 142 |
def parse_kv_args(self, args): |
| 143 |
"""parse key-value style arguments""" |
| 144 |
for arg in FIELDS: |
| 145 |
value = args.pop(arg, None) |
| 146 |
if value is not None: |
| 147 |
self.set_option(arg, value) |
| 148 |
if args: |
| 149 |
raise AnsibleError( |
| 150 |
"unrecognized arguments to with_sequence: %s" |
| 151 |
% list(args.keys()) |
| 152 |
) |
| 153 |
|
| 154 |
def parse_simple_args(self, term): |
| 155 |
"""parse the shortcut forms, return True/False""" |
| 156 |
match = SHORTCUT.match(term) |
| 157 |
if not match: |
| 158 |
return False |
| 159 |
|
| 160 |
dummy, start, end, dummy, stride, dummy, format = match.groups() |
| 161 |
|
| 162 |
for key in FIELDS: |
| 163 |
value = locals().get(key, None) |
| 164 |
if value is not None: |
| 165 |
self.set_option(key, value) |
| 166 |
|
| 167 |
return True |
| 168 |
|
| 169 |
def set_fields(self): |
| 170 |
for f in FIELDS: |
| 171 |
setattr(self, f, self.get_option(f)) |
| 172 |
|
| 173 |
def sanity_check(self): |
| 174 |
""" |
| 175 |
Returns True if options comprise a valid sequence expression |
| 176 |
Raises AnsibleError if options are an invalid expression |
| 177 |
Returns false if options are valid but result in an empty sequence - these cases do not raise exceptions |
| 178 |
in order to maintain historic behavior |
| 179 |
""" |
| 180 |
if self.count is None and self.end is None: |
| 181 |
raise AnsibleError("must specify count or end in with_sequence") |
| 182 |
elif self.count is not None and self.end is not None: |
| 183 |
raise AnsibleError("can't specify both count and end in with_sequence") |
| 184 |
elif self.count is not None: |
| 185 |
# convert count to end |
| 186 |
if self.count != 0: |
| 187 |
self.end = self.start + self.count * self.stride - 1 |
| 188 |
else: |
| 189 |
return False |
| 190 |
if self.stride > 0 and self.end < self.start: |
| 191 |
raise AnsibleError("to count backwards make stride negative") |
| 192 |
if self.stride < 0 and self.end > self.start: |
| 193 |
raise AnsibleError("to count forward don't make stride negative") |
| 194 |
if self.stride == 0: |
| 195 |
return False |
| 196 |
if self.format.count('%') != 1: |
| 197 |
raise AnsibleError("bad formatting string: %s" % self.format) |
| 198 |
|
| 199 |
return True |
| 200 |
|
| 201 |
def generate_sequence(self): |
| 202 |
if self.stride >= 0: |
| 203 |
adjust = 1 |
| 204 |
else: |
| 205 |
adjust = -1 |
| 206 |
numbers = range(self.start, self.end + adjust, self.stride) |
| 207 |
|
| 208 |
for i in numbers: |
| 209 |
try: |
| 210 |
formatted = self.format % i |
| 211 |
yield formatted |
| 212 |
except (ValueError, TypeError): |
| 213 |
raise AnsibleError( |
| 214 |
"problem formatting %r with %r" % (i, self.format) |
| 215 |
) |
| 216 |
|
| 217 |
def run(self, terms, variables=None, **kwargs): |
| 218 |
results = [] |
| 219 |
|
| 220 |
if kwargs and not terms: |
| 221 |
# All of the necessary arguments can be provided as keywords, but we still need something to loop over |
| 222 |
terms = [''] |
| 223 |
|
| 224 |
for term in terms: |
| 225 |
try: |
| 226 |
# set defaults/global |
| 227 |
self.set_options(direct=kwargs) |
| 228 |
try: |
| 229 |
if not self.parse_simple_args(term): |
| 230 |
self.parse_kv_args(parse_kv(term)) |
| 231 |
except AnsibleError: |
| 232 |
raise |
| 233 |
except Exception as e: |
| 234 |
raise AnsibleError("unknown error parsing with_sequence arguments: %r. Error was: %s" % (term, e)) |
| 235 |
|
| 236 |
self.set_fields() |
| 237 |
if self.sanity_check(): |
| 238 |
results.extend(self.generate_sequence()) |
| 239 |
|
| 240 |
except AnsibleError: |
| 241 |
raise |
| 242 |
except Exception as e: |
| 243 |
raise AnsibleError( |
| 244 |
"unknown error generating sequence: %s" % e |
| 245 |
) |
| 246 |
|
| 247 |
return results |