1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
|
#!/usr/bin/python
# Copyright: (c) 2020, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: setup_collections
short_description: Set up test collections based on the input
description:
- Builds and publishes a whole bunch of collections used for testing in bulk.
options:
server:
description:
- The Galaxy server to upload the collections to.
required: yes
type: str
token:
description:
- The token used to authenticate with the Galaxy server.
required: yes
type: str
collections:
description:
- A list of collection details to use for the build.
required: yes
type: list
elements: dict
options:
namespace:
description:
- The namespace of the collection.
required: yes
type: str
name:
description:
- The name of the collection.
required: yes
type: str
version:
description:
- The version of the collection.
type: str
default: '1.0.0'
dependencies:
description:
- The dependencies of the collection.
type: dict
default: '{}'
author:
- Jordan Borean (@jborean93)
'''
EXAMPLES = '''
- name: Build test collections
setup_collections:
path: ~/ansible/collections/ansible_collections
collections:
- namespace: namespace1
name: name1
version: 0.0.1
- namespace: namespace1
name: name1
version: 0.0.2
'''
RETURN = '''
#
'''
import os
import subprocess
import tarfile
import tempfile
import yaml
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_bytes
from functools import partial
from multiprocessing import dummy as threading
from multiprocessing import TimeoutError
COLLECTIONS_BUILD_AND_PUBLISH_TIMEOUT = 120
def publish_collection(module, collection):
namespace = collection['namespace']
name = collection['name']
version = collection['version']
dependencies = collection['dependencies']
use_symlink = collection['use_symlink']
result = {}
collection_dir = os.path.join(module.tmpdir, "%s-%s-%s" % (namespace, name, version))
b_collection_dir = to_bytes(collection_dir, errors='surrogate_or_strict')
os.mkdir(b_collection_dir)
with open(os.path.join(b_collection_dir, b'README.md'), mode='wb') as fd:
fd.write(b"Collection readme")
galaxy_meta = {
'namespace': namespace,
'name': name,
'version': version,
'readme': 'README.md',
'authors': ['Collection author <name@email.com'],
'dependencies': dependencies,
'license': ['GPL-3.0-or-later'],
'repository': 'https://ansible.com/',
}
with open(os.path.join(b_collection_dir, b'galaxy.yml'), mode='wb') as fd:
fd.write(to_bytes(yaml.safe_dump(galaxy_meta), errors='surrogate_or_strict'))
with tempfile.NamedTemporaryFile(mode='wb') as temp_fd:
temp_fd.write(b"data")
if use_symlink:
os.mkdir(os.path.join(b_collection_dir, b'docs'))
os.mkdir(os.path.join(b_collection_dir, b'plugins'))
b_target_file = b'RE\xc3\x85DM\xc3\x88.md'
with open(os.path.join(b_collection_dir, b_target_file), mode='wb') as fd:
fd.write(b'data')
os.symlink(b_target_file, os.path.join(b_collection_dir, b_target_file + b'-link'))
os.symlink(temp_fd.name, os.path.join(b_collection_dir, b_target_file + b'-outside-link'))
os.symlink(os.path.join(b'..', b_target_file), os.path.join(b_collection_dir, b'docs', b_target_file))
os.symlink(os.path.join(b_collection_dir, b_target_file),
os.path.join(b_collection_dir, b'plugins', b_target_file))
os.symlink(b'docs', os.path.join(b_collection_dir, b'docs-link'))
release_filename = '%s-%s-%s.tar.gz' % (namespace, name, version)
collection_path = os.path.join(collection_dir, release_filename)
rc, stdout, stderr = module.run_command(['ansible-galaxy', 'collection', 'build'], cwd=collection_dir)
result['build'] = {
'rc': rc,
'stdout': stdout,
'stderr': stderr,
}
if module.params['signature_dir'] is not None:
# To test user-provided signatures, we need to sign the MANIFEST.json before publishing
# Extract the tarfile to sign the MANIFEST.json
with tarfile.open(collection_path, mode='r') as collection_tar:
collection_tar.extractall(path=os.path.join(collection_dir, '%s-%s-%s' % (namespace, name, version)))
manifest_path = os.path.join(collection_dir, '%s-%s-%s' % (namespace, name, version), 'MANIFEST.json')
signature_path = os.path.join(module.params['signature_dir'], '%s-%s-%s-MANIFEST.json.asc' % (namespace, name, version))
sign_manifest(signature_path, manifest_path, module, result)
# Create the tarfile containing the signed MANIFEST.json
with tarfile.open(collection_path, "w:gz") as tar:
tar.add(os.path.join(collection_dir, '%s-%s-%s' % (namespace, name, version)), arcname=os.path.sep)
publish_args = ['ansible-galaxy', 'collection', 'publish', collection_path, '--server', module.params['server']]
if module.params['token']:
publish_args.extend(['--token', module.params['token']])
rc, stdout, stderr = module.run_command(publish_args)
result['publish'] = {
'rc': rc,
'stdout': stdout,
'stderr': stderr,
}
return result
def sign_manifest(signature_path, manifest_path, module, collection_setup_result):
collection_setup_result['gpg_detach_sign'] = {'signature_path': signature_path}
status_fd_read, status_fd_write = os.pipe()
gpg_cmd = [
"gpg",
"--batch",
"--pinentry-mode",
"loopback",
"--yes",
"--homedir",
module.params['signature_dir'],
"--detach-sign",
"--armor",
"--output",
signature_path,
manifest_path,
]
try:
p = subprocess.Popen(
gpg_cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
pass_fds=(status_fd_write,),
encoding='utf8',
)
except (FileNotFoundError, subprocess.SubprocessError) as err:
collection_setup_result['gpg_detach_sign']['error'] = "Failed during GnuPG verification with command '{gpg_cmd}': {err}".format(
gpg_cmd=gpg_cmd, err=err
)
else:
stdout, stderr = p.communicate()
collection_setup_result['gpg_detach_sign']['stdout'] = stdout
if stderr:
error = "Failed during GnuPG verification with command '{gpg_cmd}':\n{stderr}".format(gpg_cmd=gpg_cmd, stderr=stderr)
collection_setup_result['gpg_detach_sign']['error'] = error
finally:
os.close(status_fd_write)
def run_module():
module_args = dict(
server=dict(type='str', required=True),
token=dict(type='str'),
collections=dict(
type='list',
elements='dict',
required=True,
options=dict(
namespace=dict(type='str', required=True),
name=dict(type='str', required=True),
version=dict(type='str', default='1.0.0'),
dependencies=dict(type='dict', default={}),
use_symlink=dict(type='bool', default=False),
),
),
signature_dir=dict(type='path', default=None),
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=False
)
result = dict(changed=True, results=[])
pool = threading.Pool(4)
publish_func = partial(publish_collection, module)
try:
result['results'] = pool.map_async(
publish_func, module.params['collections'],
).get(timeout=COLLECTIONS_BUILD_AND_PUBLISH_TIMEOUT)
except TimeoutError as timeout_err:
module.fail_json(
'Timed out waiting for collections to be provisioned.',
)
failed = bool(sum(
r['build']['rc'] + r['publish']['rc'] for r in result['results']
))
module.exit_json(failed=failed, **result)
def main():
run_module()
if __name__ == '__main__':
main()
|