| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2012, Stephen Fromm <[email protected]> |
| 4 |
# Copyright: (c) 2016, Toshio Kuratomi <[email protected]> |
| 5 |
# Copyright: (c) 2017, Ansible Project |
| 6 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
|
| 11 |
DOCUMENTATION = r""" |
| 12 |
--- |
| 13 |
module: assemble |
| 14 |
short_description: Assemble configuration files from fragments |
| 15 |
description: |
| 16 |
- Assembles a configuration file from fragments. |
| 17 |
- Often a particular program will take a single configuration file and does not support a |
| 18 |
C(conf.d) style structure where it is easy to build up the configuration |
| 19 |
from multiple sources. M(ansible.builtin.assemble) will take a directory of files that can be |
| 20 |
local or have already been transferred to the system, and concatenate them |
| 21 |
together to produce a destination file. |
| 22 |
- Files are assembled in string sorting order. |
| 23 |
- Puppet calls this idea I(fragments). |
| 24 |
version_added: '0.5' |
| 25 |
options: |
| 26 |
src: |
| 27 |
description: |
| 28 |
- An already existing directory full of source files. |
| 29 |
type: path |
| 30 |
required: true |
| 31 |
dest: |
| 32 |
description: |
| 33 |
- A file to create using the concatenation of all of the source files. |
| 34 |
type: path |
| 35 |
required: true |
| 36 |
backup: |
| 37 |
description: |
| 38 |
- Create a backup file (if V(true)), including the timestamp information so |
| 39 |
you can get the original file back if you somehow clobbered it |
| 40 |
incorrectly. |
| 41 |
type: bool |
| 42 |
default: no |
| 43 |
delimiter: |
| 44 |
description: |
| 45 |
- A delimiter to separate the file contents. |
| 46 |
type: str |
| 47 |
version_added: '1.4' |
| 48 |
remote_src: |
| 49 |
description: |
| 50 |
- If V(false), it will search for src at originating/master machine. |
| 51 |
- If V(true), it will go to the remote/target machine for the src. |
| 52 |
type: bool |
| 53 |
default: yes |
| 54 |
version_added: '1.4' |
| 55 |
regexp: |
| 56 |
description: |
| 57 |
- Assemble files only if the given regular expression matches the filename. |
| 58 |
- If not set, all files are assembled. |
| 59 |
- Every V(\\) (backslash) must be escaped as V(\\\\) to comply to YAML syntax. |
| 60 |
- Uses L(Python regular expressions,https://docs.python.org/3/library/re.html). |
| 61 |
type: str |
| 62 |
ignore_hidden: |
| 63 |
description: |
| 64 |
- A boolean that controls if files that start with a C(.) will be included or not. |
| 65 |
type: bool |
| 66 |
default: no |
| 67 |
version_added: '2.0' |
| 68 |
validate: |
| 69 |
description: |
| 70 |
- The validation command to run before copying into place. |
| 71 |
- The path to the file to validate is passed in by C(%s) which must be present as in the sshd example below. |
| 72 |
- The command is passed securely so shell features like expansion and pipes won't work. |
| 73 |
type: str |
| 74 |
version_added: '2.0' |
| 75 |
attributes: |
| 76 |
action: |
| 77 |
support: full |
| 78 |
async: |
| 79 |
support: none |
| 80 |
bypass_host_loop: |
| 81 |
support: none |
| 82 |
check_mode: |
| 83 |
support: full |
| 84 |
diff_mode: |
| 85 |
support: full |
| 86 |
platform: |
| 87 |
platforms: posix |
| 88 |
safe_file_operations: |
| 89 |
support: full |
| 90 |
vault: |
| 91 |
support: full |
| 92 |
version_added: '2.2' |
| 93 |
seealso: |
| 94 |
- module: ansible.builtin.copy |
| 95 |
- module: ansible.builtin.template |
| 96 |
- module: ansible.windows.win_copy |
| 97 |
author: |
| 98 |
- Stephen Fromm (@sfromm) |
| 99 |
extends_documentation_fragment: |
| 100 |
- action_common_attributes |
| 101 |
- action_common_attributes.flow |
| 102 |
- action_common_attributes.files |
| 103 |
- decrypt |
| 104 |
- files |
| 105 |
""" |
| 106 |
|
| 107 |
EXAMPLES = r""" |
| 108 |
- name: Assemble from fragments from a directory |
| 109 |
ansible.builtin.assemble: |
| 110 |
src: /etc/someapp/fragments |
| 111 |
dest: /etc/someapp/someapp.conf |
| 112 |
|
| 113 |
- name: Insert the provided delimiter between fragments |
| 114 |
ansible.builtin.assemble: |
| 115 |
src: /etc/someapp/fragments |
| 116 |
dest: /etc/someapp/someapp.conf |
| 117 |
delimiter: '### START FRAGMENT ###' |
| 118 |
|
| 119 |
- name: Assemble a new "sshd_config" file into place, after passing validation with sshd |
| 120 |
ansible.builtin.assemble: |
| 121 |
src: /etc/ssh/conf.d/ |
| 122 |
dest: /etc/ssh/sshd_config |
| 123 |
validate: /usr/sbin/sshd -t -f %s |
| 124 |
""" |
| 125 |
|
| 126 |
RETURN = r"""#""" |
| 127 |
|
| 128 |
import codecs |
| 129 |
import os |
| 130 |
import re |
| 131 |
import tempfile |
| 132 |
|
| 133 |
from ansible.module_utils.basic import AnsibleModule |
| 134 |
from ansible.module_utils.common.text.converters import to_native |
| 135 |
|
| 136 |
|
| 137 |
def assemble_from_fragments(src_path, delimiter=None, compiled_regexp=None, ignore_hidden=False, tmpdir=None): |
| 138 |
""" assemble a file from a directory of fragments """ |
| 139 |
tmpfd, temp_path = tempfile.mkstemp(dir=tmpdir) |
| 140 |
tmp = os.fdopen(tmpfd, 'wb') |
| 141 |
delimit_me = False |
| 142 |
add_newline = False |
| 143 |
b_linesep = os.linesep.encode() |
| 144 |
|
| 145 |
for f in sorted(os.listdir(src_path)): |
| 146 |
if compiled_regexp and not compiled_regexp.search(f): |
| 147 |
continue |
| 148 |
fragment = os.path.join(src_path, f) |
| 149 |
if not os.path.isfile(fragment) or (ignore_hidden and os.path.basename(fragment).startswith('.')): |
| 150 |
continue |
| 151 |
with open(fragment, 'rb') as fragment_fh: |
| 152 |
fragment_content = fragment_fh.read() |
| 153 |
|
| 154 |
# always put a newline between fragments if the previous fragment didn't end with a newline. |
| 155 |
if add_newline: |
| 156 |
tmp.write(b_linesep) |
| 157 |
|
| 158 |
# delimiters should only appear between fragments |
| 159 |
if delimit_me: |
| 160 |
if delimiter: |
| 161 |
# un-escape anything like newlines |
| 162 |
delimiter = codecs.escape_decode(delimiter)[0] |
| 163 |
tmp.write(delimiter) |
| 164 |
# always make sure there's a newline after the |
| 165 |
# delimiter, so lines don't run together |
| 166 |
if not delimiter.endswith(b_linesep): |
| 167 |
tmp.write(b_linesep) |
| 168 |
|
| 169 |
tmp.write(fragment_content) |
| 170 |
delimit_me = True |
| 171 |
if fragment_content.endswith(b_linesep): |
| 172 |
add_newline = False |
| 173 |
else: |
| 174 |
add_newline = True |
| 175 |
|
| 176 |
tmp.close() |
| 177 |
return temp_path |
| 178 |
|
| 179 |
|
| 180 |
def cleanup(module, path, result=None): |
| 181 |
# cleanup just in case |
| 182 |
if os.path.exists(path): |
| 183 |
try: |
| 184 |
os.remove(path) |
| 185 |
except OSError as ex: |
| 186 |
# don't error on possible race conditions, but keep warning |
| 187 |
if result is not None: |
| 188 |
module.error_as_warning(f'Unable to remove temp file {path!r}.', exception=ex) |
| 189 |
|
| 190 |
|
| 191 |
def main(): |
| 192 |
|
| 193 |
module = AnsibleModule( |
| 194 |
# not checking because of daisy chain to file module |
| 195 |
argument_spec=dict( |
| 196 |
src=dict(type='path', required=True), |
| 197 |
delimiter=dict(type='str'), |
| 198 |
dest=dict(type='path', required=True), |
| 199 |
backup=dict(type='bool', default=False), |
| 200 |
remote_src=dict(type='bool', default=True), |
| 201 |
regexp=dict(type='str'), |
| 202 |
ignore_hidden=dict(type='bool', default=False), |
| 203 |
validate=dict(type='str'), |
| 204 |
|
| 205 |
# Options that are for the action plugin, but ignored by the module itself. |
| 206 |
# We have them here so that the tests pass without ignores, which |
| 207 |
# reduces the likelihood of further bugs added. |
| 208 |
decrypt=dict(type='bool', default=True), |
| 209 |
), |
| 210 |
add_file_common_args=True, |
| 211 |
supports_check_mode=True, |
| 212 |
) |
| 213 |
|
| 214 |
changed = False |
| 215 |
path_hash = None |
| 216 |
dest_hash = None |
| 217 |
src = module.params['src'] |
| 218 |
dest = module.params['dest'] |
| 219 |
backup = module.params['backup'] |
| 220 |
delimiter = module.params['delimiter'] |
| 221 |
regexp = module.params['regexp'] |
| 222 |
compiled_regexp = None |
| 223 |
ignore_hidden = module.params['ignore_hidden'] |
| 224 |
validate = module.params.get('validate', None) |
| 225 |
|
| 226 |
result = dict(src=src, dest=dest) |
| 227 |
if not os.path.exists(src): |
| 228 |
module.fail_json(msg="Source (%s) does not exist" % src) |
| 229 |
|
| 230 |
if not os.path.isdir(src): |
| 231 |
module.fail_json(msg="Source (%s) is not a directory" % src) |
| 232 |
|
| 233 |
if regexp is not None: |
| 234 |
try: |
| 235 |
compiled_regexp = re.compile(regexp) |
| 236 |
except re.error as e: |
| 237 |
module.fail_json(msg="Invalid Regexp (%s) in \"%s\"" % (to_native(e), regexp)) |
| 238 |
|
| 239 |
if validate and "%s" not in validate: |
| 240 |
module.fail_json(msg="validate must contain %%s: %s" % validate) |
| 241 |
|
| 242 |
path = assemble_from_fragments(src, delimiter, compiled_regexp, ignore_hidden, module.tmpdir) |
| 243 |
path_hash = module.sha1(path) |
| 244 |
result['checksum'] = path_hash |
| 245 |
|
| 246 |
# Backwards compat. This won't return data if FIPS mode is active |
| 247 |
try: |
| 248 |
pathmd5 = module.md5(path) |
| 249 |
except ValueError: |
| 250 |
pathmd5 = None |
| 251 |
result['md5sum'] = pathmd5 |
| 252 |
|
| 253 |
if os.path.exists(dest): |
| 254 |
dest_hash = module.sha1(dest) |
| 255 |
|
| 256 |
if path_hash != dest_hash: |
| 257 |
if validate: |
| 258 |
(rc, out, err) = module.run_command(validate % path) |
| 259 |
result['validation'] = dict(rc=rc, stdout=out, stderr=err) |
| 260 |
if rc != 0: |
| 261 |
cleanup(module, path) |
| 262 |
module.fail_json(msg="failed to validate: rc:%s error:%s" % (rc, err)) |
| 263 |
if backup and dest_hash is not None: |
| 264 |
result['backup_file'] = module.backup_local(dest) |
| 265 |
|
| 266 |
if not module.check_mode: |
| 267 |
module.atomic_move(path, dest, unsafe_writes=module.params['unsafe_writes']) |
| 268 |
changed = True |
| 269 |
|
| 270 |
cleanup(module, path, result) |
| 271 |
|
| 272 |
# handle file permissions (check mode aware) |
| 273 |
file_args = module.load_file_common_arguments(module.params) |
| 274 |
result['changed'] = module.set_fs_attributes_if_different(file_args, changed) |
| 275 |
|
| 276 |
# Mission complete |
| 277 |
result['msg'] = "OK" |
| 278 |
module.exit_json(**result) |
| 279 |
|
| 280 |
|
| 281 |
if __name__ == '__main__': |
| 282 |
main() |