status
stringclasses 1
value | repo_name
stringclasses 31
values | repo_url
stringclasses 31
values | issue_id
int64 1
104k
| title
stringlengths 4
233
| body
stringlengths 0
186k
⌀ | issue_url
stringlengths 38
56
| pull_url
stringlengths 37
54
| before_fix_sha
stringlengths 40
40
| after_fix_sha
stringlengths 40
40
| report_datetime
timestamp[us, tz=UTC] | language
stringclasses 5
values | commit_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 7
188
| chunk_content
stringlengths 1
1.03M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
''' Return MD5 hex digest of local file using digest_from_file().
Do not use this function unless you have no other choice for:
1) Optional backwards compatibility
2) Compatibility with a third party protocol
This function will not work on systems complying with FIPS-140-2.
Most uses of this function can use the module.sha1 function instead.
'''
if 'md5' not in AVAILABLE_HASH_ALGORITHMS:
raise ValueError('MD5 not available. Possibly running in FIPS mode')
return self.digest_from_file(filename, 'md5')
def sha1(self, filename):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
''' Return SHA1 hex digest of local file using digest_from_file(). '''
return self.digest_from_file(filename, 'sha1')
def sha256(self, filename):
''' Return SHA-256 hex digest of local file using digest_from_file(). '''
return self.digest_from_file(filename, 'sha256')
def backup_local(self, fn):
'''make a date-marked backup of the specified file, return True or False on success or failure'''
backupdest = ''
if os.path.exists(fn):
ext = time.strftime("%Y-%m-%d@%H:%M:%S~", time.localtime(time.time()))
backupdest = '%s.%s.%s' % (fn, os.getpid(), ext)
try:
self.preserved_copy(fn, backupdest)
except (shutil.Error, IOError) as e:
self.fail_json(msg='Could not make backup of %s to %s: %s' % (fn, backupdest, to_native(e)))
return backupdest
def cleanup(self, tmpfile):
if os.path.exists(tmpfile):
try:
os.unlink(tmpfile)
except OSError as e:
sys.stderr.write("could not cleanup %s: %s" % (tmpfile, to_native(e)))
def preserved_copy(self, src, dest):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
"""Copy a file with preserved ownership, permissions and context"""
#
shutil.copy2(src, dest)
if self.selinux_enabled():
context = self.selinux_context(src)
self.set_context_if_different(dest, context, False)
try:
dest_stat = os.stat(src)
tmp_stat = os.stat(dest)
if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
os.chown(dest, dest_stat.st_uid, dest_stat.st_gid)
except OSError as e:
if e.errno != errno.EPERM:
raise
current_attribs = self.get_file_attributes(src, include_version=False)
current_attribs = current_attribs.get('attr_flags', '')
self.set_attributes_if_different(dest, current_attribs, True)
def atomic_move(self, src, dest, unsafe_writes=False):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
'''atomically move src to dest, copying attributes from dest, returns true on success
it uses os.rename to ensure this as it is an atomic operation, rest of the function is
to work around limitations, corner cases and ensure selinux context is saved if possible'''
context = None
dest_stat = None
b_src = to_bytes(src, errors='surrogate_or_strict')
b_dest = to_bytes(dest, errors='surrogate_or_strict')
if os.path.exists(b_dest):
try:
dest_stat = os.stat(b_dest)
os.chmod(b_src, dest_stat.st_mode & PERM_BITS)
os.chown(b_src, dest_stat.st_uid, dest_stat.st_gid)
if hasattr(os, 'chflags') and hasattr(dest_stat, 'st_flags'):
try:
os.chflags(b_src, dest_stat.st_flags)
except OSError as e:
for err in 'EOPNOTSUPP', 'ENOTSUP':
if hasattr(errno, err) and e.errno == getattr(errno, err):
break
else:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
raise
except OSError as e:
if e.errno != errno.EPERM:
raise
if self.selinux_enabled():
context = self.selinux_context(dest)
else:
if self.selinux_enabled():
context = self.selinux_default_context(dest)
creating = not os.path.exists(b_dest)
try:
os.rename(b_src, b_dest)
except (IOError, OSError) as e:
if e.errno not in [errno.EPERM, errno.EXDEV, errno.EACCES, errno.ETXTBSY, errno.EBUSY]:
self.fail_json(msg='Could not replace file: %s to %s: %s' % (src, dest, to_native(e)), exception=traceback.format_exc())
else:
b_dest_dir = os.path.dirname(b_dest)
b_suffix = os.path.basename(b_dest)
error_msg = None
tmp_dest_name = None
try:
tmp_dest_fd, tmp_dest_name = tempfile.mkstemp(prefix=b'.ansible_tmp', dir=b_dest_dir, suffix=b_suffix)
except (OSError, IOError) as e:
error_msg = 'The destination directory (%s) is not writable by the current user. Error was: %s' % (os.path.dirname(dest), to_native(e))
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
finally:
if error_msg:
if unsafe_writes:
self._unsafe_writes(b_src, b_dest)
else:
self.fail_json(msg=error_msg, exception=traceback.format_exc())
if tmp_dest_name:
b_tmp_dest_name = to_bytes(tmp_dest_name, errors='surrogate_or_strict')
try:
try:
os.close(tmp_dest_fd)
try:
shutil.move(b_src, b_tmp_dest_name)
except OSError:
shutil.copy2(b_src, b_tmp_dest_name)
if self.selinux_enabled():
self.set_context_if_different(
b_tmp_dest_name, context, False)
try:
tmp_stat = os.stat(b_tmp_dest_name)
if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
os.chown(b_tmp_dest_name, dest_stat.st_uid, dest_stat.st_gid)
except OSError as e:
if e.errno != errno.EPERM:
raise
try:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
os.rename(b_tmp_dest_name, b_dest)
except (shutil.Error, OSError, IOError) as e:
if unsafe_writes and e.errno == errno.EBUSY:
self._unsafe_writes(b_tmp_dest_name, b_dest)
else:
self.fail_json(msg='Unable to make %s into to %s, failed final rename from %s: %s' %
(src, dest, b_tmp_dest_name, to_native(e)), exception=traceback.format_exc())
except (shutil.Error, OSError, IOError) as e:
if unsafe_writes:
self._unsafe_writes(b_src, b_dest)
else:
self.fail_json(msg='Failed to replace file: %s to %s: %s' % (src, dest, to_native(e)), exception=traceback.format_exc())
finally:
self.cleanup(b_tmp_dest_name)
if creating:
umask = os.umask(0)
os.umask(umask)
os.chmod(b_dest, DEFAULT_PERM & ~umask)
try:
os.chown(b_dest, os.geteuid(), os.getegid())
except OSError:
pass
if self.selinux_enabled():
self.set_context_if_different(dest, context, False)
def _unsafe_writes(self, src, dest):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
try:
out_dest = in_src = None
try:
out_dest = open(dest, 'wb')
in_src = open(src, 'rb')
shutil.copyfileobj(in_src, out_dest)
finally:
if out_dest:
out_dest.close()
if in_src:
in_src.close()
except (shutil.Error, OSError, IOError) as e:
self.fail_json(msg='Could not write data to file (%s) from (%s): %s' % (dest, src, to_native(e)),
exception=traceback.format_exc())
def _clean_args(self, args):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
if not self._clean:
to_clean_args = args
if PY2:
if isinstance(args, text_type):
to_clean_args = to_bytes(args)
else:
if isinstance(args, binary_type):
to_clean_args = to_text(args)
if isinstance(args, (text_type, binary_type)):
to_clean_args = shlex.split(to_clean_args)
clean_args = []
is_passwd = False
for arg in (to_native(a) for a in to_clean_args):
if is_passwd:
is_passwd = False
clean_args.append('********')
continue
if PASSWD_ARG_RE.match(arg):
sep_idx = arg.find('=')
if sep_idx > -1:
clean_args.append('%s=********' % arg[:sep_idx])
continue
else:
is_passwd = True
arg = heuristic_log_sanitize(arg, self.no_log_values)
clean_args.append(arg)
self._clean = ' '.join(shlex_quote(arg) for arg in clean_args)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
return self._clean
def _restore_signal_handlers(self):
if PY2 and sys.platform != 'win32':
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def run_command(self, args, check_rc=False, close_fds=True, executable=None, data=None, binary_data=False, path_prefix=None, cwd=None,
use_unsafe_shell=False, prompt_regex=None, environ_update=None, umask=None, encoding='utf-8', errors='surrogate_or_strict',
expand_user_and_vars=True, pass_fds=None, before_communicate_callback=None, ignore_invalid_cwd=True, handle_exceptions=True):
'''
Execute a command, returns rc, stdout, and stderr.
The mechanism of this method for reading stdout and stderr differs from
that of CPython subprocess.Popen.communicate, in that this method will
stop reading once the spawned command has exited and stdout and stderr
have been consumed, as opposed to waiting until stdout/stderr are
closed. This can be an important distinction, when taken into account
that a forked or backgrounded process may hold stdout or stderr open
for longer than the spawned command.
:arg args: is the command to run
* If args is a list, the command will be run with shell=False.
* If args is a string and use_unsafe_shell=False it will split args to a list and run with shell=False
* If args is a string and use_unsafe_shell=True it runs with shell=True.
:kw check_rc: Whether to call fail_json in case of non zero RC.
Default False
:kw close_fds: See documentation for subprocess.Popen(). Default True
:kw executable: See documentation for subprocess.Popen(). Default None
:kw data: If given, information to write to the stdin of the command
:kw binary_data: If False, append a newline to the data. Default False
:kw path_prefix: If given, additional path to find the command in.
This adds to the PATH environment variable so helper commands in
the same directory can also be found
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
:kw cwd: If given, working directory to run the command inside
:kw use_unsafe_shell: See `args` parameter. Default False
:kw prompt_regex: Regex string (not a compiled regex) which can be
used to detect prompts in the stdout which would otherwise cause
the execution to hang (especially if no input data is specified)
:kw environ_update: dictionary to *update* environ variables with
:kw umask: Umask to be used when running the command. Default None
:kw encoding: Since we return native strings, on python3 we need to
know the encoding to use to transform from bytes to text. If you
want to always get bytes back, use encoding=None. The default is
"utf-8". This does not affect transformation of strings given as
args.
:kw errors: Since we return native strings, on python3 we need to
transform stdout and stderr from bytes to text. If the bytes are
undecodable in the ``encoding`` specified, then use this error
handler to deal with them. The default is ``surrogate_or_strict``
which means that the bytes will be decoded using the
surrogateescape error handler if available (available on all
python3 versions we support) otherwise a UnicodeError traceback
will be raised. This does not affect transformations of strings
given as args.
:kw expand_user_and_vars: When ``use_unsafe_shell=False`` this argument
dictates whether ``~`` is expanded in paths and environment variables
are expanded before running the command. When ``True`` a string such as
``$SHELL`` will be expanded regardless of escaping. When ``False`` and
``use_unsafe_shell=False`` no path or variable expansion will be done.
:kw pass_fds: When running on Python 3 this argument
dictates which file descriptors should be passed
to an underlying ``Popen`` constructor. On Python 2, this will
set ``close_fds`` to False.
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
:kw before_communicate_callback: This function will be called
after ``Popen`` object will be created
but before communicating to the process.
(``Popen`` object will be passed to callback as a first argument)
:kw ignore_invalid_cwd: This flag indicates whether an invalid ``cwd``
(non-existent or not a directory) should be ignored or should raise
an exception.
:kw handle_exceptions: This flag indicates whether an exception will
be handled inline and issue a failed_json or if the caller should
handle it.
:returns: A 3-tuple of return code (integer), stdout (native string),
and stderr (native string). On python2, stdout and stderr are both
byte strings. On python3, stdout and stderr are text strings converted
according to the encoding and errors parameters. If you want byte
strings on python3, use encoding=None to turn decoding to text off.
'''
self._clean = None
if not isinstance(args, (list, binary_type, text_type)):
msg = "Argument 'args' to run_command must be list or string"
self.fail_json(rc=257, cmd=args, msg=msg)
shell = False
if use_unsafe_shell:
if isinstance(args, list):
args = b" ".join([to_bytes(shlex_quote(x), errors='surrogate_or_strict') for x in args])
else:
args = to_bytes(args, errors='surrogate_or_strict')
if executable:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
executable = to_bytes(executable, errors='surrogate_or_strict')
args = [executable, b'-c', args]
elif self._shell not in (None, '/bin/sh'):
args = [to_bytes(self._shell, errors='surrogate_or_strict'), b'-c', args]
else:
shell = True
else:
if isinstance(args, (binary_type, text_type)):
if PY2:
args = to_bytes(args, errors='surrogate_or_strict')
elif PY3:
args = to_text(args, errors='surrogateescape')
args = shlex.split(args)
if expand_user_and_vars:
args = [to_bytes(os.path.expanduser(os.path.expandvars(x)), errors='surrogate_or_strict') for x in args if x is not None]
else:
args = [to_bytes(x, errors='surrogate_or_strict') for x in args if x is not None]
prompt_re = None
if prompt_regex:
if isinstance(prompt_regex, text_type):
if PY3:
prompt_regex = to_bytes(prompt_regex, errors='surrogateescape')
elif PY2:
prompt_regex = to_bytes(prompt_regex, errors='surrogate_or_strict')
try:
prompt_re = re.compile(prompt_regex, re.MULTILINE)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
except re.error:
self.fail_json(msg="invalid prompt regular expression given to run_command")
rc = 0
msg = None
st_in = None
env = os.environ.copy()
env.update(self.run_command_environ_update or {})
env.update(environ_update or {})
if path_prefix:
path = env.get('PATH', '')
if path:
env['PATH'] = "%s:%s" % (path_prefix, path)
else:
env['PATH'] = path_prefix
if 'PYTHONPATH' in env:
pypaths = [x for x in env['PYTHONPATH'].split(':')
if x and
not x.endswith('/ansible_modlib.zip') and
not x.endswith('/debug_dir')]
if pypaths and any(pypaths):
env['PYTHONPATH'] = ':'.join(pypaths)
if data:
st_in = subprocess.PIPE
def preexec():
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
self._restore_signal_handlers()
if umask:
os.umask(umask)
kwargs = dict(
executable=executable,
shell=shell,
close_fds=close_fds,
stdin=st_in,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
preexec_fn=preexec,
env=env,
)
if PY3 and pass_fds:
kwargs["pass_fds"] = pass_fds
elif PY2 and pass_fds:
kwargs['close_fds'] = False
if cwd:
cwd = to_bytes(os.path.abspath(os.path.expanduser(cwd)), errors='surrogate_or_strict')
if os.path.isdir(cwd):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
kwargs['cwd'] = cwd
elif not ignore_invalid_cwd:
self.fail_json(msg="Provided cwd is not a valid directory: %s" % cwd)
try:
if self._debug:
self.log('Executing: ' + self._clean_args(args))
cmd = subprocess.Popen(args, **kwargs)
if before_communicate_callback:
before_communicate_callback(cmd)
stdout = b''
stderr = b''
if hasattr(selectors, 'PollSelector'):
selector = selectors.PollSelector()
else:
selector = selectors.SelectSelector()
if data:
if not binary_data:
data += '\n'
if isinstance(data, text_type):
data = to_bytes(data)
selector.register(cmd.stdout, selectors.EVENT_READ)
selector.register(cmd.stderr, selectors.EVENT_READ)
if os.name == 'posix':
fcntl.fcntl(cmd.stdout.fileno(), fcntl.F_SETFL, fcntl.fcntl(cmd.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK)
fcntl.fcntl(cmd.stderr.fileno(), fcntl.F_SETFL, fcntl.fcntl(cmd.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK)
if data:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
cmd.stdin.write(data)
cmd.stdin.close()
while True:
events = selector.select(1)
stdout_changed = False
for key, event in events:
b_chunk = key.fileobj.read(32768)
if not b_chunk:
selector.unregister(key.fileobj)
elif key.fileobj == cmd.stdout:
stdout += b_chunk
stdout_changed = True
elif key.fileobj == cmd.stderr:
stderr += b_chunk
if prompt_re and stdout_changed and prompt_re.search(stdout) and not data:
if encoding:
stdout = to_native(stdout, encoding=encoding, errors=errors)
return (257, stdout, "A prompt was encountered while running a command, but no input data was specified")
if (not events or not selector.get_map()) and cmd.poll() is not None:
break
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
elif not selector.get_map() and cmd.poll() is None:
cmd.wait()
break
cmd.stdout.close()
cmd.stderr.close()
selector.close()
rc = cmd.returncode
except (OSError, IOError) as e:
self.log("Error Executing CMD:%s Exception:%s" % (self._clean_args(args), to_native(e)))
if handle_exceptions:
self.fail_json(rc=e.errno, stdout=b'', stderr=b'', msg=to_native(e), cmd=self._clean_args(args))
else:
raise e
except Exception as e:
self.log("Error Executing CMD:%s Exception:%s" % (self._clean_args(args), to_native(traceback.format_exc())))
if handle_exceptions:
self.fail_json(rc=257, stdout=b'', stderr=b'', msg=to_native(e), exception=traceback.format_exc(), cmd=self._clean_args(args))
else:
raise e
if rc != 0 and check_rc:
msg = heuristic_log_sanitize(stderr.rstrip(), self.no_log_values)
self.fail_json(cmd=self._clean_args(args), rc=rc, stdout=stdout, stderr=stderr, msg=msg)
if encoding is not None:
return (rc, to_native(stdout, encoding=encoding, errors=errors),
to_native(stderr, encoding=encoding, errors=errors))
return (rc, stdout, stderr)
def append_to_file(self, filename, str):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
filename = os.path.expandvars(os.path.expanduser(filename))
fh = open(filename, 'a')
fh.write(str)
fh.close()
def bytes_to_human(self, size):
return bytes_to_human(size)
pretty_bytes = bytes_to_human
def human_to_bytes(self, number, isbits=False):
return human_to_bytes(number, isbits)
#
#
is_executable = is_executable
@staticmethod
def get_buffer_size(fd):
try:
buffer_size = fcntl.fcntl(fd, 1032)
except Exception:
try:
buffer_size = select.PIPE_BUF
except Exception:
buffer_size = 9000
return buffer_size
def get_module_path():
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/basic.py
|
return os.path.dirname(os.path.realpath(__file__))
def __getattr__(importable_name):
"""Inject import-time deprecation warnings.
Specifically, for ``literal_eval()``, ``_literal_eval()``
and ``get_exception()``.
"""
if importable_name == 'get_exception':
deprecate(
msg=f'The `ansible.module_utils.basic.'
f'{importable_name}` function is deprecated.',
version='2.19',
)
from ansible.module_utils.pycompat24 import get_exception
return get_exception
if importable_name in {'literal_eval', '_literal_eval'}:
deprecate(
msg=f'The `ansible.module_utils.basic.'
f'{importable_name}` function is deprecated.',
version='2.19',
)
from ast import literal_eval
return literal_eval
raise AttributeError(
f'cannot import name {importable_name !r} '
f'has no attribute ({__file__ !s})',
)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
from __future__ import annotations
import datetime
import os
from collections import deque
from itertools import chain
from ansible.module_utils.common.collections import is_iterable
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
from ansible.module_utils.common.warnings import warn
from ansible.module_utils.errors import (
AliasError,
AnsibleFallbackNotFound,
AnsibleValidationErrorMultiple,
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
ArgumentTypeError,
ArgumentValueError,
ElementError,
MutuallyExclusiveError,
NoLogError,
RequiredByError,
RequiredError,
RequiredIfError,
RequiredOneOfError,
RequiredTogetherError,
SubParameterTypeError,
)
from ansible.module_utils.parsing.convert_bool import BOOLEANS_FALSE, BOOLEANS_TRUE
from ansible.module_utils.six.moves.collections_abc import (
KeysView,
Set,
Sequence,
Mapping,
MutableMapping,
MutableSet,
MutableSequence,
)
from ansible.module_utils.six import (
binary_type,
integer_types,
string_types,
text_type,
PY2,
PY3,
)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
from ansible.module_utils.common.validation import (
check_mutually_exclusive,
check_required_arguments,
check_required_together,
check_required_one_of,
check_required_if,
check_required_by,
check_type_bits,
check_type_bool,
check_type_bytes,
check_type_dict,
check_type_float,
check_type_int,
check_type_jsonarg,
check_type_list,
check_type_path,
check_type_raw,
check_type_str,
)
NoneType = type(None)
_ADDITIONAL_CHECKS = (
{'func': check_required_together, 'attr': 'required_together', 'err': RequiredTogetherError},
{'func': check_required_one_of, 'attr': 'required_one_of', 'err': RequiredOneOfError},
{'func': check_required_if, 'attr': 'required_if', 'err': RequiredIfError},
{'func': check_required_by, 'attr': 'required_by', 'err': RequiredByError},
)
PASS_VARS = {
'check_mode': ('check_mode', False),
'debug': ('_debug', False),
'diff': ('_diff', False),
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
'keep_remote_files': ('_keep_remote_files', False),
'ignore_unknown_opts': ('_ignore_unknown_opts', False),
'module_name': ('_name', None),
'no_log': ('no_log', False),
'remote_tmp': ('_remote_tmp', None),
'selinux_special_fs': ('_selinux_special_fs', ['fuse', 'nfs', 'vboxsf', 'ramfs', '9p', 'vfat']),
'shell_executable': ('_shell', '/bin/sh'),
'socket': ('_socket_path', None),
'string_conversion_action': ('_string_conversion_action', 'warn'),
'syslog_facility': ('_syslog_facility', 'INFO'),
'tmpdir': ('_tmpdir', None),
'verbosity': ('_verbosity', 0),
'version': ('ansible_version', '0.0'),
}
PASS_BOOLS = ('check_mode', 'debug', 'diff', 'keep_remote_files', 'ignore_unknown_opts', 'no_log')
DEFAULT_TYPE_VALIDATORS = {
'str': check_type_str,
'list': check_type_list,
'dict': check_type_dict,
'bool': check_type_bool,
'int': check_type_int,
'float': check_type_float,
'path': check_type_path,
'raw': check_type_raw,
'jsonarg': check_type_jsonarg,
'json': check_type_jsonarg,
'bytes': check_type_bytes,
'bits': check_type_bits,
}
def _get_type_validator(wanted):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
"""Returns the callable used to validate a wanted type and the type name.
:arg wanted: String or callable. If a string, get the corresponding
validation function from DEFAULT_TYPE_VALIDATORS. If callable,
get the name of the custom callable and return that for the type_checker.
:returns: Tuple of callable function or None, and a string that is the name
of the wanted type.
"""
if not callable(wanted):
if wanted is None:
wanted = 'str'
type_checker = DEFAULT_TYPE_VALIDATORS.get(wanted)
else:
type_checker = wanted
wanted = getattr(wanted, '__name__', to_native(type(wanted)))
return type_checker, wanted
def _get_legal_inputs(argument_spec, parameters, aliases=None):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
if aliases is None:
aliases = _handle_aliases(argument_spec, parameters)
return list(aliases.keys()) + list(argument_spec.keys())
def _get_unsupported_parameters(argument_spec, parameters, legal_inputs=None, options_context=None, store_supported=None):
"""Check keys in parameters against those provided in legal_inputs
to ensure they contain legal values. If legal_inputs are not supplied,
they will be generated using the argument_spec.
:arg argument_spec: Dictionary of parameters, their type, and valid values.
:arg parameters: Dictionary of parameters.
:arg legal_inputs: List of valid key names property names. Overrides values
in argument_spec.
:arg options_context: List of parent keys for tracking the context of where
a parameter is defined.
:returns: Set of unsupported parameters. Empty set if no unsupported parameters
are found.
"""
if legal_inputs is None:
legal_inputs = _get_legal_inputs(argument_spec, parameters)
unsupported_parameters = set()
for k in parameters.keys():
if k not in legal_inputs:
context = k
if options_context:
context = tuple(options_context + [k])
unsupported_parameters.add(context)
if store_supported is not None:
supported_aliases = _handle_aliases(argument_spec, parameters)
supported_params = []
for option in legal_inputs:
if option in supported_aliases:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
continue
supported_params.append(option)
store_supported.update({context: (supported_params, supported_aliases)})
return unsupported_parameters
def _handle_aliases(argument_spec, parameters, alias_warnings=None, alias_deprecations=None):
"""Process aliases from an argument_spec including warnings and deprecations.
Modify ``parameters`` by adding a new key for each alias with the supplied
value from ``parameters``.
If a list is provided to the alias_warnings parameter, it will be filled with tuples
(option, alias) in every case where both an option and its alias are specified.
If a list is provided to alias_deprecations, it will be populated with dictionaries,
each containing deprecation information for each alias found in argument_spec.
:param argument_spec: Dictionary of parameters, their type, and valid values.
:type argument_spec: dict
:param parameters: Dictionary of parameters.
:type parameters: dict
:param alias_warnings:
:type alias_warnings: list
:param alias_deprecations:
:type alias_deprecations: list
"""
aliases_results = {}
for (k, v) in argument_spec.items():
aliases = v.get('aliases', None)
default = v.get('default', None)
required = v.get('required', False)
if alias_deprecations is not None:
for alias in argument_spec[k].get('deprecated_aliases', []):
if alias.get('name') in parameters:
alias_deprecations.append(alias)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
if default is not None and required:
raise ValueError("internal error: required and default are mutually exclusive for %s" % k)
if aliases is None:
continue
if not is_iterable(aliases) or isinstance(aliases, (binary_type, text_type)):
raise TypeError('internal error: aliases must be a list or tuple')
for alias in aliases:
aliases_results[alias] = k
if alias in parameters:
if k in parameters and alias_warnings is not None:
alias_warnings.append((k, alias))
parameters[k] = parameters[alias]
return aliases_results
def _list_deprecations(argument_spec, parameters, prefix=''):
"""Return a list of deprecations
:arg argument_spec: An argument spec dictionary
:arg parameters: Dictionary of parameters
:returns: List of dictionaries containing a message and version in which
the deprecated parameter will be removed, or an empty list.
:Example return:
.. code-block:: python
[
{
'msg': "Param 'deptest' is deprecated. See the module docs for more information",
'version': '2.9'
}
]
"""
deprecations = []
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
for arg_name, arg_opts in argument_spec.items():
if arg_name in parameters:
if prefix:
sub_prefix = '%s["%s"]' % (prefix, arg_name)
else:
sub_prefix = arg_name
if arg_opts.get('removed_at_date') is not None:
deprecations.append({
'msg': "Param '%s' is deprecated. See the module docs for more information" % sub_prefix,
'date': arg_opts.get('removed_at_date'),
'collection_name': arg_opts.get('removed_from_collection'),
})
elif arg_opts.get('removed_in_version') is not None:
deprecations.append({
'msg': "Param '%s' is deprecated. See the module docs for more information" % sub_prefix,
'version': arg_opts.get('removed_in_version'),
'collection_name': arg_opts.get('removed_from_collection'),
})
sub_argument_spec = arg_opts.get('options')
if sub_argument_spec is not None:
sub_arguments = parameters[arg_name]
if isinstance(sub_arguments, Mapping):
sub_arguments = [sub_arguments]
if isinstance(sub_arguments, list):
for sub_params in sub_arguments:
if isinstance(sub_params, Mapping):
deprecations.extend(_list_deprecations(sub_argument_spec, sub_params, prefix=sub_prefix))
return deprecations
def _list_no_log_values(argument_spec, params):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
"""Return set of no log values
:arg argument_spec: An argument spec dictionary
:arg params: Dictionary of all parameters
:returns: :class:`set` of strings that should be hidden from output:
"""
no_log_values = set()
for arg_name, arg_opts in argument_spec.items():
if arg_opts.get('no_log', False):
no_log_object = params.get(arg_name, None)
if no_log_object:
try:
no_log_values.update(_return_datastructure_name(no_log_object))
except TypeError as e:
raise TypeError('Failed to convert "%s": %s' % (arg_name, to_native(e)))
sub_argument_spec = arg_opts.get('options')
if sub_argument_spec is not None:
wanted_type = arg_opts.get('type')
sub_parameters = params.get(arg_name)
if sub_parameters is not None:
if wanted_type == 'dict' or (wanted_type == 'list' and arg_opts.get('elements', '') == 'dict'):
if not isinstance(sub_parameters, list):
sub_parameters = [sub_parameters]
for sub_param in sub_parameters:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
if isinstance(sub_param, string_types):
sub_param = check_type_dict(sub_param)
if not isinstance(sub_param, Mapping):
raise TypeError("Value '{1}' in the sub parameter field '{0}' must by a {2}, "
"not '{1.__class__.__name__}'".format(arg_name, sub_param, wanted_type))
no_log_values.update(_list_no_log_values(sub_argument_spec, sub_param))
return no_log_values
def _return_datastructure_name(obj):
""" Return native stringified values from datastructures.
For use with removing sensitive values pre-jsonification."""
if isinstance(obj, (text_type, binary_type)):
if obj:
yield to_native(obj, errors='surrogate_or_strict')
return
elif isinstance(obj, Mapping):
for element in obj.items():
for subelement in _return_datastructure_name(element[1]):
yield subelement
elif is_iterable(obj):
for element in obj:
for subelement in _return_datastructure_name(element):
yield subelement
elif obj is None or isinstance(obj, bool):
return
elif isinstance(obj, tuple(list(integer_types) + [float])):
yield to_native(obj, nonstring='simplerepr')
else:
raise TypeError('Unknown parameter type: %s' % (type(obj)))
def _remove_values_conditions(value, no_log_strings, deferred_removals):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
"""
Helper function for :meth:`remove_values`.
:arg value: The value to check for strings that need to be stripped
:arg no_log_strings: set of strings which must be stripped out of any values
:arg deferred_removals: List which holds information about nested
containers that have to be iterated for removals. It is passed into
this function so that more entries can be added to it if value is
a container type. The format of each entry is a 2-tuple where the first
element is the ``value`` parameter and the second value is a new
container to copy the elements of ``value`` into once iterated.
:returns: if ``value`` is a scalar, returns ``value`` with two exceptions:
1. :class:`~datetime.datetime` objects which are changed into a string representation.
2. objects which are in ``no_log_strings`` are replaced with a placeholder
so that no sensitive data is leaked.
If ``value`` is a container type, returns a new empty container.
``deferred_removals`` is added to as a side-effect of this function.
.. warning:: It is up to the caller to make sure the order in which value
is passed in is correct. For instance, higher level containers need
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
to be passed in before lower level containers. For example, given
``{'level1': {'level2': 'level3': [True]} }`` first pass in the
dictionary for ``level1``, then the dict for ``level2``, and finally
the list for ``level3``.
"""
if isinstance(value, (text_type, binary_type)):
native_str_value = value
if isinstance(value, text_type):
value_is_text = True
if PY2:
native_str_value = to_bytes(value, errors='surrogate_or_strict')
elif isinstance(value, binary_type):
value_is_text = False
if PY3:
native_str_value = to_text(value, errors='surrogate_or_strict')
if native_str_value in no_log_strings:
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
for omit_me in no_log_strings:
native_str_value = native_str_value.replace(omit_me, '*' * 8)
if value_is_text and isinstance(native_str_value, binary_type):
value = to_text(native_str_value, encoding='utf-8', errors='surrogate_then_replace')
elif not value_is_text and isinstance(native_str_value, text_type):
value = to_bytes(native_str_value, encoding='utf-8', errors='surrogate_then_replace')
else:
value = native_str_value
elif isinstance(value, Sequence):
if isinstance(value, MutableSequence):
new_value = type(value)()
else:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
new_value = []
deferred_removals.append((value, new_value))
value = new_value
elif isinstance(value, Set):
if isinstance(value, MutableSet):
new_value = type(value)()
else:
new_value = set()
deferred_removals.append((value, new_value))
value = new_value
elif isinstance(value, Mapping):
if isinstance(value, MutableMapping):
new_value = type(value)()
else:
new_value = {}
deferred_removals.append((value, new_value))
value = new_value
elif isinstance(value, tuple(chain(integer_types, (float, bool, NoneType)))):
stringy_value = to_native(value, encoding='utf-8', errors='surrogate_or_strict')
if stringy_value in no_log_strings:
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
for omit_me in no_log_strings:
if omit_me in stringy_value:
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
elif isinstance(value, (datetime.datetime, datetime.date)):
value = value.isoformat()
else:
raise TypeError('Value of unknown type: %s, %s' % (type(value), value))
return value
def _set_defaults(argument_spec, parameters, set_default=True):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
"""Set default values for parameters when no value is supplied.
Modifies parameters directly.
:arg argument_spec: Argument spec
:type argument_spec: dict
:arg parameters: Parameters to evaluate
:type parameters: dict
:kwarg set_default: Whether or not to set the default values
:type set_default: bool
:returns: Set of strings that should not be logged.
:rtype: set
"""
no_log_values = set()
for param, value in argument_spec.items():
default = value.get('default', None)
if param not in parameters and (default is not None or set_default):
if value.get('no_log', False) and default:
no_log_values.add(default)
parameters[param] = default
return no_log_values
def _sanitize_keys_conditions(value, no_log_strings, ignore_keys, deferred_removals):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
""" Helper method to :func:`sanitize_keys` to build ``deferred_removals`` and avoid deep recursion. """
if isinstance(value, (text_type, binary_type)):
return value
if isinstance(value, Sequence):
if isinstance(value, MutableSequence):
new_value = type(value)()
else:
new_value = []
deferred_removals.append((value, new_value))
return new_value
if isinstance(value, Set):
if isinstance(value, MutableSet):
new_value = type(value)()
else:
new_value = set()
deferred_removals.append((value, new_value))
return new_value
if isinstance(value, Mapping):
if isinstance(value, MutableMapping):
new_value = type(value)()
else:
new_value = {}
deferred_removals.append((value, new_value))
return new_value
if isinstance(value, tuple(chain(integer_types, (float, bool, NoneType)))):
return value
if isinstance(value, (datetime.datetime, datetime.date)):
return value
raise TypeError('Value of unknown type: %s, %s' % (type(value), value))
def _validate_elements(wanted_type, parameter, values, options_context=None, errors=None):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
if errors is None:
errors = AnsibleValidationErrorMultiple()
type_checker, wanted_element_type = _get_type_validator(wanted_type)
validated_parameters = []
kwargs = {}
if wanted_element_type == 'str' and isinstance(wanted_type, string_types):
if isinstance(parameter, string_types):
kwargs['param'] = parameter
elif isinstance(parameter, dict):
kwargs['param'] = list(parameter.keys())[0]
for value in values:
try:
validated_parameters.append(type_checker(value, **kwargs))
except (TypeError, ValueError) as e:
msg = "Elements value for option '%s'" % parameter
if options_context:
msg += " found in '%s'" % " -> ".join(options_context)
msg += " is of type %s and we were unable to convert to %s: %s" % (type(value), wanted_element_type, to_native(e))
errors.append(ElementError(msg))
return validated_parameters
def _validate_argument_types(argument_spec, parameters, prefix='', options_context=None, errors=None):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
"""Validate that parameter types match the type in the argument spec.
Determine the appropriate type checker function and run each
parameter value through that function. All error messages from type checker
functions are returned. If any parameter fails to validate, it will not
be in the returned parameters.
:arg argument_spec: Argument spec
:type argument_spec: dict
:arg parameters: Parameters
:type parameters: dict
:kwarg prefix: Name of the parent key that contains the spec. Used in the error message
:type prefix: str
:kwarg options_context: List of contexts?
:type options_context: list
:returns: Two item tuple containing validated and coerced parameters
and a list of any errors that were encountered.
:rtype: tuple
"""
if errors is None:
errors = AnsibleValidationErrorMultiple()
for param, spec in argument_spec.items():
if param not in parameters:
continue
value = parameters[param]
if value is None and not spec.get('required') and spec.get('default') is None:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
continue
wanted_type = spec.get('type')
type_checker, wanted_name = _get_type_validator(wanted_type)
kwargs = {}
if wanted_name == 'str' and isinstance(wanted_type, string_types):
kwargs['param'] = list(parameters.keys())[0]
if prefix:
kwargs['prefix'] = prefix
try:
parameters[param] = type_checker(value, **kwargs)
elements_wanted_type = spec.get('elements', None)
if elements_wanted_type:
elements = parameters[param]
if wanted_type != 'list' or not isinstance(elements, list):
msg = "Invalid type %s for option '%s'" % (wanted_name, elements)
if options_context:
msg += " found in '%s'." % " -> ".join(options_context)
msg += ", elements value check is supported only with 'list' type"
errors.append(ArgumentTypeError(msg))
parameters[param] = _validate_elements(elements_wanted_type, param, elements, options_context, errors)
except (TypeError, ValueError) as e:
msg = "argument '%s' is of type %s" % (param, type(value))
if options_context:
msg += " found in '%s'." % " -> ".join(options_context)
msg += " and we were unable to convert to %s: %s" % (wanted_name, to_native(e))
errors.append(ArgumentTypeError(msg))
def _validate_argument_values(argument_spec, parameters, options_context=None, errors=None):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
"""Ensure all arguments have the requested values, and there are no stray arguments"""
if errors is None:
errors = AnsibleValidationErrorMultiple()
for param, spec in argument_spec.items():
choices = spec.get('choices')
if choices is None:
continue
if isinstance(choices, (frozenset, KeysView, Sequence)) and not isinstance(choices, (binary_type, text_type)):
if param in parameters:
if isinstance(parameters[param], list):
diff_list = [item for item in parameters[param] if item not in choices]
if diff_list:
choices_str = ", ".join([to_native(c) for c in choices])
diff_str = ", ".join(diff_list)
msg = "value of %s must be one or more of: %s. Got no match for: %s" % (param, choices_str, diff_str)
if options_context:
msg = "{0} found in {1}".format(msg, " -> ".join(options_context))
errors.append(ArgumentValueError(msg))
elif parameters[param] not in choices:
if parameters[param] == 'False':
overlap = BOOLEANS_FALSE.intersection(choices)
if len(overlap) == 1:
(parameters[param],) = overlap
if parameters[param] == 'True':
overlap = BOOLEANS_TRUE.intersection(choices)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
if len(overlap) == 1:
(parameters[param],) = overlap
if parameters[param] not in choices:
choices_str = ", ".join([to_native(c) for c in choices])
msg = "value of %s must be one of: %s, got: %s" % (param, choices_str, parameters[param])
if options_context:
msg = "{0} found in {1}".format(msg, " -> ".join(options_context))
errors.append(ArgumentValueError(msg))
else:
msg = "internal error: choices for argument %s are not iterable: %s" % (param, choices)
if options_context:
msg = "{0} found in {1}".format(msg, " -> ".join(options_context))
errors.append(ArgumentTypeError(msg))
def _validate_sub_spec(
argument_spec,
parameters,
prefix="",
options_context=None,
errors=None,
no_log_values=None,
unsupported_parameters=None,
supported_parameters=None,
alias_deprecations=None,
):
"""Validate sub argument spec.
This function is recursive.
"""
if options_context is None:
options_context = []
if errors is None:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
errors = AnsibleValidationErrorMultiple()
if no_log_values is None:
no_log_values = set()
if unsupported_parameters is None:
unsupported_parameters = set()
if supported_parameters is None:
supported_parameters = dict()
for param, value in argument_spec.items():
wanted = value.get('type')
if wanted == 'dict' or (wanted == 'list' and value.get('elements', '') == 'dict'):
sub_spec = value.get('options')
if value.get('apply_defaults', False):
if sub_spec is not None:
if parameters.get(param) is None:
parameters[param] = {}
else:
continue
elif sub_spec is None or param not in parameters or parameters[param] is None:
continue
options_context.append(param)
if not isinstance(parameters[param], Sequence) or isinstance(parameters[param], string_types):
elements = [parameters[param]]
else:
elements = parameters[param]
for idx, sub_parameters in enumerate(elements):
no_log_values.update(set_fallbacks(sub_spec, sub_parameters))
if not isinstance(sub_parameters, dict):
errors.append(SubParameterTypeError("value of '%s' must be of type dict or list of dicts" % param))
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
continue
new_prefix = prefix + param
if wanted == 'list':
new_prefix += '[%d]' % idx
new_prefix += '.'
alias_warnings = []
alias_deprecations_sub = []
try:
options_aliases = _handle_aliases(sub_spec, sub_parameters, alias_warnings, alias_deprecations_sub)
except (TypeError, ValueError) as e:
options_aliases = {}
errors.append(AliasError(to_native(e)))
for option, alias in alias_warnings:
warn('Both option %s%s and its alias %s%s are set.' % (new_prefix, option, new_prefix, alias))
if alias_deprecations is not None:
for deprecation in alias_deprecations_sub:
alias_deprecations.append({
'name': '%s%s' % (new_prefix, deprecation['name']),
'version': deprecation.get('version'),
'date': deprecation.get('date'),
'collection_name': deprecation.get('collection_name'),
})
try:
no_log_values.update(_list_no_log_values(sub_spec, sub_parameters))
except TypeError as te:
errors.append(NoLogError(to_native(te)))
legal_inputs = _get_legal_inputs(sub_spec, sub_parameters, options_aliases)
unsupported_parameters.update(
_get_unsupported_parameters(
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
sub_spec,
sub_parameters,
legal_inputs,
options_context,
store_supported=supported_parameters,
)
)
try:
check_mutually_exclusive(value.get('mutually_exclusive'), sub_parameters, options_context)
except TypeError as e:
errors.append(MutuallyExclusiveError(to_native(e)))
no_log_values.update(_set_defaults(sub_spec, sub_parameters, False))
try:
check_required_arguments(sub_spec, sub_parameters, options_context)
except TypeError as e:
errors.append(RequiredError(to_native(e)))
_validate_argument_types(sub_spec, sub_parameters, new_prefix, options_context, errors=errors)
_validate_argument_values(sub_spec, sub_parameters, options_context, errors=errors)
for check in _ADDITIONAL_CHECKS:
try:
check['func'](value.get(check['attr']), sub_parameters, options_context)
except TypeError as e:
errors.append(check['err'](to_native(e)))
no_log_values.update(_set_defaults(sub_spec, sub_parameters))
_validate_sub_spec(
sub_spec, sub_parameters, new_prefix, options_context, errors, no_log_values,
unsupported_parameters, supported_parameters, alias_deprecations)
options_context.pop()
def env_fallback(*args, **kwargs):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
"""Load value from environment variable"""
for arg in args:
if arg in os.environ:
return os.environ[arg]
raise AnsibleFallbackNotFound
def set_fallbacks(argument_spec, parameters):
no_log_values = set()
for param, value in argument_spec.items():
fallback = value.get('fallback', (None,))
fallback_strategy = fallback[0]
fallback_args = []
fallback_kwargs = {}
if param not in parameters and fallback_strategy is not None:
for item in fallback[1:]:
if isinstance(item, dict):
fallback_kwargs = item
else:
fallback_args = item
try:
fallback_value = fallback_strategy(*fallback_args, **fallback_kwargs)
except AnsibleFallbackNotFound:
continue
else:
if value.get('no_log', False) and fallback_value:
no_log_values.add(fallback_value)
parameters[param] = fallback_value
return no_log_values
def sanitize_keys(obj, no_log_strings, ignore_keys=frozenset()):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
"""Sanitize the keys in a container object by removing ``no_log`` values from key names.
This is a companion function to the :func:`remove_values` function. Similar to that function,
we make use of ``deferred_removals`` to avoid hitting maximum recursion depth in cases of
large data structures.
:arg obj: The container object to sanitize. Non-container objects are returned unmodified.
:arg no_log_strings: A set of string values we do not want logged.
:kwarg ignore_keys: A set of string values of keys to not sanitize.
:returns: An object with sanitized keys.
"""
deferred_removals = deque()
no_log_strings = [to_native(s, errors='surrogate_or_strict') for s in no_log_strings]
new_value = _sanitize_keys_conditions(obj, no_log_strings, ignore_keys, deferred_removals)
while deferred_removals:
old_data, new_data = deferred_removals.popleft()
if isinstance(new_data, Mapping):
for old_key, old_elem in old_data.items():
if old_key in ignore_keys or old_key.startswith('_ansible'):
new_data[old_key] = _sanitize_keys_conditions(old_elem, no_log_strings, ignore_keys, deferred_removals)
else:
new_key = _remove_values_conditions(old_key, no_log_strings, None)
new_data[new_key] = _sanitize_keys_conditions(old_elem, no_log_strings, ignore_keys, deferred_removals)
else:
for elem in old_data:
new_elem = _sanitize_keys_conditions(elem, no_log_strings, ignore_keys, deferred_removals)
if isinstance(new_data, MutableSequence):
new_data.append(new_elem)
elif isinstance(new_data, MutableSet):
new_data.add(new_elem)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/module_utils/common/parameters.py
|
else:
raise TypeError('Unknown container type encountered when removing private values from keys')
return new_value
def remove_values(value, no_log_strings):
"""Remove strings in ``no_log_strings`` from value.
If value is a container type, then remove a lot more.
Use of ``deferred_removals`` exists, rather than a pure recursive solution,
because of the potential to hit the maximum recursion depth when dealing with
large amounts of data (see `issue #24560 <https://github.com/ansible/ansible/issues/24560>`_).
"""
deferred_removals = deque()
no_log_strings = [to_native(s, errors='surrogate_or_strict') for s in no_log_strings]
new_value = _remove_values_conditions(value, no_log_strings, deferred_removals)
while deferred_removals:
old_data, new_data = deferred_removals.popleft()
if isinstance(new_data, Mapping):
for old_key, old_elem in old_data.items():
new_elem = _remove_values_conditions(old_elem, no_log_strings, deferred_removals)
new_data[old_key] = new_elem
else:
for elem in old_data:
new_elem = _remove_values_conditions(elem, no_log_strings, deferred_removals)
if isinstance(new_data, MutableSequence):
new_data.append(new_elem)
elif isinstance(new_data, MutableSet):
new_data.add(new_elem)
else:
raise TypeError('Unknown container type encountered when removing private values from output')
return new_value
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
from __future__ import annotations
import base64
import json
import os
import random
import re
import shlex
import stat
import tempfile
from abc import ABC, abstractmethod
from collections.abc import Sequence
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleConnectionFailure, AnsibleActionSkip, AnsibleActionFail, AnsibleAuthenticationFailure
from ansible.executor.module_common import modify_module
from ansible.executor.interpreter_discovery import discover_interpreter, InterpreterDiscoveryRequiredError
from ansible.module_utils.common.arg_spec import ArgumentSpecValidator
from ansible.module_utils.errors import UnsupportedError
from ansible.module_utils.json_utils import _filter_non_json_lines
from ansible.module_utils.six import binary_type, string_types, text_type
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
from ansible.parsing.utils.jsonify import jsonify
from ansible.release import __version__
from ansible.utils.collection_loader import resource_from_fqcr
from ansible.utils.display import Display
from ansible.utils.unsafe_proxy import wrap_var, AnsibleUnsafeText
from ansible.vars.clean import remove_internal_keys
from ansible.utils.plugin_docs import get_versioned_doclink
display = Display()
def _validate_utf8_json(d):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
if isinstance(d, text_type):
d.encode(encoding='utf-8', errors='strict')
elif isinstance(d, dict):
for o in d.items():
_validate_utf8_json(o)
elif isinstance(d, (list, tuple)):
for o in d:
_validate_utf8_json(o)
class ActionBase(ABC):
'''
This class is the base class for all action plugins, and defines
code common to all actions. The base class handles the connection
by putting/getting files and executing commands based on the current
action in use.
'''
_VALID_ARGS = frozenset([])
BYPASS_HOST_LOOP = False
TRANSFERS_FILES = False
_requires_connection = True
_supports_check_mode = True
_supports_async = False
def __init__(self, task, connection, play_context, loader, templar, shared_loader_obj):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
self._task = task
self._connection = connection
self._play_context = play_context
self._loader = loader
self._templar = templar
self._shared_loader_obj = shared_loader_obj
self._cleanup_remote_tmp = False
self._discovered_interpreter_key = None
self._discovered_interpreter = False
self._discovery_deprecation_warnings = []
self._discovery_warnings = []
self._used_interpreter = None
self._display = display
@abstractmethod
def run(self, tmp=None, task_vars=None):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
""" Action Plugins should implement this method to perform their
tasks. Everything else in this base class is a helper method for the
action plugin to do that.
:kwarg tmp: Deprecated parameter. This is no longer used. An action plugin that calls
another one and wants to use the same remote tmp for both should set
self._connection._shell.tmpdir rather than this parameter.
:kwarg task_vars: The variables (host vars, group vars, config vars,
etc) associated with this task.
:returns: dictionary of results from the module
Implementers of action modules may find the following variables especially useful:
* Module parameters. These are stored in self._task.args
"""
result = {}
if tmp is not None:
result['warning'] = ['ActionModule.run() no longer honors the tmp parameter. Action'
' plugins should set self._connection._shell.tmpdir to share'
' the tmpdir']
del tmp
if self._task.async_val and not self._supports_async:
raise AnsibleActionFail('async is not supported for this task.')
elif self._task.check_mode and not self._supports_check_mode:
raise AnsibleActionSkip('check mode is not supported for this task.')
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
elif self._task.async_val and self._task.check_mode:
raise AnsibleActionFail('check mode and async cannot be used on same task.')
if self._VALID_ARGS:
task_opts = frozenset(self._task.args.keys())
bad_opts = task_opts.difference(self._VALID_ARGS)
if bad_opts:
raise AnsibleActionFail('Invalid options for %s: %s' % (self._task.action, ','.join(list(bad_opts))))
if self._connection._shell.tmpdir is None and self._early_needs_tmp_path():
self._make_tmp_path()
return result
def validate_argument_spec(self, argument_spec=None,
mutually_exclusive=None,
required_together=None,
required_one_of=None,
required_if=None,
required_by=None,
):
"""Validate an argument spec against the task args
This will return a tuple of (ValidationResult, dict) where the dict
is the validated, coerced, and normalized task args.
Be cautious when directly passing ``new_module_args`` directly to a
module invocation, as it will contain the defaults, and not only
the args supplied from the task. If you do this, the module
should not define ``mututally_exclusive`` or similar.
This code is roughly copied from the ``validate_argument_spec``
action plugin for use by other action plugins.
"""
new_module_args = self._task.args.copy()
validator = ArgumentSpecValidator(
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
argument_spec,
mutually_exclusive=mutually_exclusive,
required_together=required_together,
required_one_of=required_one_of,
required_if=required_if,
required_by=required_by,
)
validation_result = validator.validate(new_module_args)
new_module_args.update(validation_result.validated_parameters)
try:
error = validation_result.errors[0]
except IndexError:
error = None
if error:
msg = validation_result.errors.msg
if isinstance(error, UnsupportedError):
msg = f"Unsupported parameters for ({self._load_name}) module: {msg}"
raise AnsibleActionFail(msg)
return validation_result, new_module_args
def cleanup(self, force=False):
"""Method to perform a clean up at the end of an action plugin execution
By default this is designed to clean up the shell tmpdir, and is toggled based on whether
async is in use
Action plugins may override this if they deem necessary, but should still call this method
via super
"""
if force or not self._task.async_val:
self._remove_tmp_path(self._connection._shell.tmpdir)
def get_plugin_option(self, plugin, option, default=None):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
"""Helper to get an option from a plugin without having to use
the try/except dance everywhere to set a default
"""
try:
return plugin.get_option(option)
except (AttributeError, KeyError):
return default
def get_become_option(self, option, default=None):
return self.get_plugin_option(self._connection.become, option, default=default)
def get_connection_option(self, option, default=None):
return self.get_plugin_option(self._connection, option, default=default)
def get_shell_option(self, option, default=None):
return self.get_plugin_option(self._connection._shell, option, default=default)
def _remote_file_exists(self, path):
cmd = self._connection._shell.exists(path)
result = self._low_level_execute_command(cmd=cmd, sudoable=True)
if result['rc'] == 0:
return True
return False
def _configure_module(self, module_name, module_args, task_vars):
'''
Handles the loading and templating of the module code through the
modify_module() function.
'''
if self._task.delegate_to:
use_vars = task_vars.get('ansible_delegated_vars')[self._task.delegate_to]
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
else:
use_vars = task_vars
split_module_name = module_name.split('.')
collection_name = '.'.join(split_module_name[0:2]) if len(split_module_name) > 2 else ''
leaf_module_name = resource_from_fqcr(module_name)
for mod_type in self._connection.module_implementation_preferences:
if mod_type == '.ps1':
win_collection = 'ansible.windows'
rewrite_collection_names = ['ansible.builtin', 'ansible.legacy', '']
if leaf_module_name in ('stat', 'file', 'copy', 'ping') and \
collection_name in rewrite_collection_names and self._task.action != module_name:
module_name = '%s.win_%s' % (win_collection, leaf_module_name)
elif leaf_module_name == 'async_status' and collection_name in rewrite_collection_names:
module_name = '%s.%s' % (win_collection, leaf_module_name)
if leaf_module_name in ['win_stat', 'win_file', 'win_copy', 'slurp'] and module_args and \
hasattr(self._connection._shell, '_unquote'):
for key in ('src', 'dest', 'path'):
if key in module_args:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
module_args[key] = self._connection._shell._unquote(module_args[key])
result = self._shared_loader_obj.module_loader.find_plugin_with_context(module_name, mod_type, collection_list=self._task.collections)
if not result.resolved:
if result.redirect_list and len(result.redirect_list) > 1:
target_module_name = result.redirect_list[-1]
raise AnsibleError("The module {0} was redirected to {1}, which could not be loaded.".format(module_name, target_module_name))
module_path = result.plugin_resolved_path
if module_path:
break
else:
raise AnsibleError("The module %s was not found in configured module paths" % (module_name))
final_environment = dict()
self._compute_environment_string(final_environment)
become_kwargs = {}
if self._connection.become:
become_kwargs['become'] = True
become_kwargs['become_method'] = self._connection.become.name
become_kwargs['become_user'] = self._connection.become.get_option('become_user',
playcontext=self._play_context)
become_kwargs['become_password'] = self._connection.become.get_option('become_pass',
playcontext=self._play_context)
become_kwargs['become_flags'] = self._connection.become.get_option('become_flags',
playcontext=self._play_context)
for dummy in (1, 2):
try:
(module_data, module_style, module_shebang) = modify_module(module_name, module_path, module_args, self._templar,
task_vars=use_vars,
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
module_compression=C.config.get_config_value('DEFAULT_MODULE_COMPRESSION',
variables=task_vars),
async_timeout=self._task.async_val,
environment=final_environment,
remote_is_local=bool(getattr(self._connection, '_remote_is_local', False)),
**become_kwargs)
break
except InterpreterDiscoveryRequiredError as idre:
self._discovered_interpreter = AnsibleUnsafeText(discover_interpreter(
action=self,
interpreter_name=idre.interpreter_name,
discovery_mode=idre.discovery_mode,
task_vars=use_vars))
discovered_key = 'discovered_interpreter_%s' % idre.interpreter_name
use_vars['ansible_facts'][discovered_key] = self._discovered_interpreter
if not self._task.delegate_to or self._task.delegate_facts:
task_vars['ansible_facts'][discovered_key] = self._discovered_interpreter
self._discovered_interpreter_key = discovered_key
else:
task_vars['ansible_delegated_vars'][self._task.delegate_to]['ansible_facts'][discovered_key] = self._discovered_interpreter
return (module_style, module_shebang, module_data, module_path)
def _compute_environment_string(self, raw_environment_out=None):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'''
Builds the environment string to be used when executing the remote task.
'''
final_environment = dict()
if self._task.environment is not None:
environments = self._task.environment
if not isinstance(environments, list):
environments = [environments]
for environment in environments:
if environment is None or len(environment) == 0:
continue
temp_environment = self._templar.template(environment)
if not isinstance(temp_environment, dict):
raise AnsibleError("environment must be a dictionary, received %s (%s)" % (temp_environment, type(temp_environment)))
final_environment.update(temp_environment)
if len(final_environment) > 0:
final_environment = self._templar.template(final_environment)
if isinstance(raw_environment_out, dict):
raw_environment_out.clear()
raw_environment_out.update(final_environment)
return self._connection._shell.env_prefix(**final_environment)
def _early_needs_tmp_path(self):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'''
Determines if a tmp path should be created before the action is executed.
'''
return getattr(self, 'TRANSFERS_FILES', False)
def _is_pipelining_enabled(self, module_style, wrap_async=False):
'''
Determines if we are required and can do pipelining
'''
try:
is_enabled = self._connection.get_option('pipelining')
except (KeyError, AttributeError, ValueError):
is_enabled = self._play_context.pipelining
always_pipeline = self._connection.always_pipeline_modules
become_exception = (self._connection.become.name if self._connection.become else '') != 'su'
conditions = [
self._connection.has_pipelining,
is_enabled or always_pipeline,
module_style == "new",
not C.DEFAULT_KEEP_REMOTE_FILES,
not wrap_async or always_pipeline,
become_exception,
]
return all(conditions)
def _get_admin_users(self):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'''
Returns a list of admin users that are configured for the current shell
plugin
'''
return self.get_shell_option('admin_users', ['root'])
def _get_remote_addr(self, tvars):
''' consistently get the 'remote_address' for the action plugin '''
remote_addr = tvars.get('delegated_vars', {}).get('ansible_host', tvars.get('ansible_host', tvars.get('inventory_hostname', None)))
for variation in ('remote_addr', 'host'):
try:
remote_addr = self._connection.get_option(variation)
except KeyError:
continue
break
else:
remote_addr = self._play_context.remote_addr
return remote_addr
def _get_remote_user(self):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
''' consistently get the 'remote_user' for the action plugin '''
remote_user = None
try:
remote_user = self._connection.get_option('remote_user')
except KeyError:
remote_user = getattr(self._connection, 'default_user', None) or self._play_context.remote_user
except AttributeError:
remote_user = self._play_context.remote_user
return remote_user
def _is_become_unprivileged(self):
'''
The user is not the same as the connection user and is not part of the
shell configured admin users
'''
if not self._connection.become:
return False
admin_users = self._get_admin_users()
remote_user = self._get_remote_user()
become_user = self.get_become_option('become_user')
return bool(become_user and become_user not in admin_users + [remote_user])
def _make_tmp_path(self, remote_user=None):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'''
Create and return a temporary path on a remote box.
'''
if getattr(self._connection, '_remote_is_local', False):
tmpdir = C.DEFAULT_LOCAL_TMP
else:
tmpdir = self._remote_expand_user(self.get_shell_option('remote_tmp', default='~/.ansible/tmp'), sudoable=False)
become_unprivileged = self._is_become_unprivileged()
basefile = self._connection._shell._generate_temp_dir_name()
cmd = self._connection._shell.mkdtemp(basefile=basefile, system=become_unprivileged, tmpdir=tmpdir)
result = self._low_level_execute_command(cmd, sudoable=False)
if result['rc'] != 0:
if result['rc'] == 5:
output = 'Authentication failure.'
elif result['rc'] == 255 and self._connection.transport in ('ssh',):
if display.verbosity > 3:
output = u'SSH encountered an unknown error. The output was:\n%s%s' % (result['stdout'], result['stderr'])
else:
output = (u'SSH encountered an unknown error during the connection. '
'We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue')
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
elif u'No space left on device' in result['stderr']:
output = result['stderr']
else:
output = ('Failed to create temporary directory. '
'In some cases, you may have been able to authenticate and did not have permissions on the target directory. '
'Consider changing the remote tmp path in ansible.cfg to a path rooted in "/tmp", for more error information use -vvv. '
'Failed command was: %s, exited with result %d' % (cmd, result['rc']))
if 'stdout' in result and result['stdout'] != u'':
output = output + u", stdout output: %s" % result['stdout']
if display.verbosity > 3 and 'stderr' in result and result['stderr'] != u'':
output += u", stderr output: %s" % result['stderr']
raise AnsibleConnectionFailure(output)
else:
self._cleanup_remote_tmp = True
try:
stdout_parts = result['stdout'].strip().split('%s=' % basefile, 1)
rc = self._connection._shell.join_path(stdout_parts[-1], u'').splitlines()[-1]
except IndexError:
rc = '/'
if rc == '/':
raise AnsibleError('failed to resolve remote temporary directory from %s: `%s` returned empty string' % (basefile, cmd))
self._connection._shell.tmpdir = rc
return rc
def _should_remove_tmp_path(self, tmp_path):
'''Determine if temporary path should be deleted or kept by user request/config'''
return tmp_path and self._cleanup_remote_tmp and not C.DEFAULT_KEEP_REMOTE_FILES and "-tmp-" in tmp_path
def _remove_tmp_path(self, tmp_path, force=False):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'''Remove a temporary path we created. '''
if tmp_path is None and self._connection._shell.tmpdir:
tmp_path = self._connection._shell.tmpdir
if force or self._should_remove_tmp_path(tmp_path):
cmd = self._connection._shell.remove(tmp_path, recurse=True)
tmp_rm_res = self._low_level_execute_command(cmd, sudoable=False)
if tmp_rm_res.get('rc', 0) != 0:
display.warning('Error deleting remote temporary files (rc: %s, stderr: %s})'
% (tmp_rm_res.get('rc'), tmp_rm_res.get('stderr', 'No error string available.')))
else:
self._connection._shell.tmpdir = None
def _transfer_file(self, local_path, remote_path):
"""
Copy a file from the controller to a remote path
:arg local_path: Path on controller to transfer
:arg remote_path: Path on the remote system to transfer into
.. warning::
* When you use this function you likely want to use use fixup_perms2() on the
remote_path to make sure that the remote file is readable when the user becomes
a non-privileged user.
* If you use fixup_perms2() on the file and copy or move the file into place, you will
need to then remove filesystem acls on the file once it has been copied into place by
the module. See how the copy module implements this for help.
"""
self._connection.put_file(local_path, remote_path)
return remote_path
def _transfer_data(self, remote_path, data):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'''
Copies the module data out to the temporary module path.
'''
if isinstance(data, dict):
data = jsonify(data)
afd, afile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP)
afo = os.fdopen(afd, 'wb')
try:
data = to_bytes(data, errors='surrogate_or_strict')
afo.write(data)
except Exception as e:
raise AnsibleError("failure writing module data to temporary file for transfer: %s" % to_native(e))
afo.flush()
afo.close()
try:
self._transfer_file(afile, remote_path)
finally:
os.unlink(afile)
return remote_path
def _fixup_perms2(self, remote_paths, remote_user=None, execute=True):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
"""
We need the files we upload to be readable (and sometimes executable)
by the user being sudo'd to but we want to limit other people's access
(because the files could contain passwords or other private
information. We achieve this in one of these ways:
* If no sudo is performed or the remote_user is sudo'ing to
themselves, we don't have to change permissions.
* If the remote_user sudo's to a privileged user (for instance, root),
we don't have to change permissions
* If the remote_user sudo's to an unprivileged user then we attempt to
grant the unprivileged user access via file system acls.
* If granting file system acls fails we try to change the owner of the
file with chown which only works in case the remote_user is
privileged or the remote systems allows chown calls by unprivileged
users (e.g. HP-UX)
* If the above fails, we next try 'chmod +a' which is a macOS way of
setting ACLs on files.
* If the above fails, we check if ansible_common_remote_group is set.
If it is, we attempt to chgrp the file to its value. This is useful
if the remote_user has a group in common with the become_user. As the
remote_user, we can chgrp the file to that group and allow the
become_user to read it.
* If (the chown fails AND ansible_common_remote_group is not set) OR
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
(ansible_common_remote_group is set AND the chgrp (or following chmod)
returned non-zero), we can set the file to be world readable so that
the second unprivileged user can read the file.
Since this could allow other users to get access to private
information we only do this if ansible is configured with
"allow_world_readable_tmpfiles" in the ansible.cfg. Also note that
when ansible_common_remote_group is set this final fallback is very
unlikely to ever be triggered, so long as chgrp was successful. But
just because the chgrp was successful, does not mean Ansible can
necessarily access the files (if, for example, the variable was set
to a group that remote_user is in, and can chgrp to, but does not have
in common with become_user).
"""
if remote_user is None:
remote_user = self._get_remote_user()
if getattr(self._connection._shell, "_IS_WINDOWS", False):
return remote_paths
if not self._is_become_unprivileged():
if execute:
res = self._remote_chmod(remote_paths, 'u+x')
if res['rc'] != 0:
raise AnsibleError(
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'Failed to set execute bit on remote files '
'(rc: {0}, err: {1})'.format(
res['rc'],
to_native(res['stderr'])))
return remote_paths
become_user = self.get_become_option('become_user')
if execute:
chmod_mode = 'rx'
setfacl_mode = 'r-x'
chmod_acl_mode = '{0} allow read,execute'.format(become_user)
posix_acl_mode = 'A+user:{0}:rx:allow'.format(become_user)
else:
chmod_mode = 'rX'
setfacl_mode = 'r-X'
chmod_acl_mode = '{0} allow read'.format(become_user)
posix_acl_mode = 'A+user:{0}:r:allow'.format(become_user)
res = self._remote_set_user_facl(
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
remote_paths,
become_user,
setfacl_mode)
if res['rc'] == 0:
return remote_paths
if execute:
res = self._remote_chmod(remote_paths, 'u+x')
if res['rc'] != 0:
raise AnsibleError(
'Failed to set file mode or acl on remote temporary files '
'(rc: {0}, err: {1})'.format(
res['rc'],
to_native(res['stderr'])))
res = self._remote_chown(remote_paths, become_user)
if res['rc'] == 0:
return remote_paths
if remote_user in self._get_admin_users():
raise AnsibleError(
'Failed to change ownership of the temporary files Ansible '
'(via chmod nor setfacl) needs to create despite connecting as a '
'privileged user. Unprivileged become user would be unable to read'
' the file.')
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
try:
res = self._remote_chmod([chmod_acl_mode] + list(remote_paths), '+a')
except AnsibleAuthenticationFailure as e:
pass
else:
if res['rc'] == 0:
return remote_paths
res = self._remote_chmod(remote_paths, posix_acl_mode)
if res['rc'] == 0:
return remote_paths
become_link = get_versioned_doclink('playbook_guide/playbooks_privilege_escalation.html')
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
#
#
group = self.get_shell_option('common_remote_group')
if group is not None:
res = self._remote_chgrp(remote_paths, group)
if res['rc'] == 0:
if self.get_shell_option('world_readable_temp'):
display.warning(
'Both common_remote_group and '
'allow_world_readable_tmpfiles are set. chgrp was '
'successful, but there is no guarantee that Ansible '
'will be able to read the files after this operation, '
'particularly if common_remote_group was set to a '
'group of which the unprivileged become user is not a '
'member. In this situation, '
'allow_world_readable_tmpfiles is a no-op. See this '
'URL for more details: %s'
'#risks-of-becoming-an-unprivileged-user' % become_link)
if execute:
group_mode = 'g+rwx'
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
else:
group_mode = 'g+rw'
res = self._remote_chmod(remote_paths, group_mode)
if res['rc'] == 0:
return remote_paths
if self.get_shell_option('world_readable_temp'):
display.warning(
'Using world-readable permissions for temporary files Ansible '
'needs to create when becoming an unprivileged user. This may '
'be insecure. For information on securing this, see %s'
'#risks-of-becoming-an-unprivileged-user' % become_link)
res = self._remote_chmod(remote_paths, 'a+%s' % chmod_mode)
if res['rc'] == 0:
return remote_paths
raise AnsibleError(
'Failed to set file mode on remote files '
'(rc: {0}, err: {1})'.format(
res['rc'],
to_native(res['stderr'])))
raise AnsibleError(
'Failed to set permissions on the temporary files Ansible needs '
'to create when becoming an unprivileged user '
'(rc: %s, err: %s}). For information on working around this, see %s'
'#risks-of-becoming-an-unprivileged-user' % (
res['rc'],
to_native(res['stderr']), become_link))
def _remote_chmod(self, paths, mode, sudoable=False):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'''
Issue a remote chmod command
'''
cmd = self._connection._shell.chmod(paths, mode)
res = self._low_level_execute_command(cmd, sudoable=sudoable)
return res
def _remote_chown(self, paths, user, sudoable=False):
'''
Issue a remote chown command
'''
cmd = self._connection._shell.chown(paths, user)
res = self._low_level_execute_command(cmd, sudoable=sudoable)
return res
def _remote_chgrp(self, paths, group, sudoable=False):
'''
Issue a remote chgrp command
'''
cmd = self._connection._shell.chgrp(paths, group)
res = self._low_level_execute_command(cmd, sudoable=sudoable)
return res
def _remote_set_user_facl(self, paths, user, mode, sudoable=False):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'''
Issue a remote call to setfacl
'''
cmd = self._connection._shell.set_user_facl(paths, user, mode)
res = self._low_level_execute_command(cmd, sudoable=sudoable)
return res
def _execute_remote_stat(self, path, all_vars, follow, tmp=None, checksum=True):
'''
Get information from remote file.
'''
if tmp is not None:
display.warning('_execute_remote_stat no longer honors the tmp parameter. Action'
' plugins should set self._connection._shell.tmpdir to share'
' the tmpdir')
del tmp
module_args = dict(
path=path,
follow=follow,
get_checksum=checksum,
get_size=False,
checksum_algorithm='sha1',
)
mystat = self._execute_module(module_name='ansible.legacy.stat', module_args=module_args, task_vars=all_vars,
wrap_async=False, ignore_unknown_opts=True)
if mystat.get('failed'):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
msg = mystat.get('module_stderr')
if not msg:
msg = mystat.get('module_stdout')
if not msg:
msg = mystat.get('msg')
raise AnsibleError('Failed to get information on remote file (%s): %s' % (path, msg))
if not mystat['stat']['exists']:
mystat['stat']['checksum'] = '1'
if 'checksum' not in mystat['stat']:
mystat['stat']['checksum'] = ''
elif not isinstance(mystat['stat']['checksum'], string_types):
raise AnsibleError("Invalid checksum returned by stat: expected a string type but got %s" % type(mystat['stat']['checksum']))
return mystat['stat']
def _remote_expand_user(self, path, sudoable=True, pathsep=None):
''' takes a remote path and performs tilde/$HOME expansion on the remote host '''
if not path.startswith('~'):
return path
split_path = path.split(os.path.sep, 1)
expand_path = split_path[0]
if expand_path == '~':
become_user = self.get_become_option('become_user')
if getattr(self._connection, '_remote_is_local', False):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
pass
elif sudoable and self._connection.become and become_user:
expand_path = '~%s' % become_user
else:
expand_path = '~%s' % (self._get_remote_user() or '')
cmd = self._connection._shell.expand_user(expand_path)
data = self._low_level_execute_command(cmd, sudoable=False)
try:
initial_fragment = data['stdout'].strip().splitlines()[-1]
except IndexError:
initial_fragment = None
if not initial_fragment:
cmd = self._connection._shell.pwd()
pwd = self._low_level_execute_command(cmd, sudoable=False).get('stdout', '').strip()
if pwd:
expanded = pwd
else:
expanded = path
elif len(split_path) > 1:
expanded = self._connection._shell.join_path(initial_fragment, *split_path[1:])
else:
expanded = initial_fragment
if '..' in os.path.dirname(expanded).split('/'):
raise AnsibleError("'%s' returned an invalid relative home directory path containing '..'" % self._get_remote_addr({}))
return expanded
def _strip_success_message(self, data):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'''
Removes the BECOME-SUCCESS message from the data.
'''
if data.strip().startswith('BECOME-SUCCESS-'):
data = re.sub(r'^((\r)?\n)?BECOME-SUCCESS.*(\r)?\n', '', data)
return data
def _update_module_args(self, module_name, module_args, task_vars, ignore_unknown_opts: bool = False):
if self._task.check_mode:
if not self._supports_check_mode:
raise AnsibleError("check mode is not supported for this operation")
module_args['_ansible_check_mode'] = True
else:
module_args['_ansible_check_mode'] = False
no_target_syslog = C.config.get_config_value('DEFAULT_NO_TARGET_SYSLOG', variables=task_vars)
module_args['_ansible_no_log'] = self._task.no_log or no_target_syslog
module_args['_ansible_debug'] = C.DEFAULT_DEBUG
module_args['_ansible_diff'] = self._task.diff
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
module_args['_ansible_verbosity'] = display.verbosity
module_args['_ansible_version'] = __version__
module_args['_ansible_module_name'] = module_name
module_args['_ansible_syslog_facility'] = task_vars.get('ansible_syslog_facility', C.DEFAULT_SYSLOG_FACILITY)
module_args['_ansible_selinux_special_fs'] = C.DEFAULT_SELINUX_SPECIAL_FS
module_args['_ansible_string_conversion_action'] = C.STRING_CONVERSION_ACTION
module_args['_ansible_socket'] = getattr(self._connection, 'socket_path')
if not module_args['_ansible_socket']:
module_args['_ansible_socket'] = task_vars.get('ansible_socket')
module_args['_ansible_shell_executable'] = self._play_context.executable
module_args['_ansible_keep_remote_files'] = C.DEFAULT_KEEP_REMOTE_FILES
if self._is_become_unprivileged():
module_args['_ansible_tmpdir'] = None
else:
module_args['_ansible_tmpdir'] = self._connection._shell.tmpdir
module_args['_ansible_remote_tmp'] = self.get_shell_option('remote_tmp', default='~/.ansible/tmp')
module_args['_ansible_ignore_unknown_opts'] = ignore_unknown_opts
def _execute_module(self, module_name=None, module_args=None, tmp=None, task_vars=None, persist_files=False, delete_remote_tmp=None, wrap_async=False,
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
ignore_unknown_opts: bool = False):
'''
Transfer and run a module along with its arguments.
'''
if tmp is not None:
display.warning('_execute_module no longer honors the tmp parameter. Action plugins'
' should set self._connection._shell.tmpdir to share the tmpdir')
del tmp
if delete_remote_tmp is not None:
display.warning('_execute_module no longer honors the delete_remote_tmp parameter.'
' Action plugins should check self._connection._shell.tmpdir to'
' see if a tmpdir existed before they were called to determine'
' if they are responsible for removing it.')
del delete_remote_tmp
tmpdir = self._connection._shell.tmpdir
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
if not self._is_pipelining_enabled("new", wrap_async) and tmpdir is None:
self._make_tmp_path()
tmpdir = self._connection._shell.tmpdir
if task_vars is None:
task_vars = dict()
if module_name is None:
module_name = self._task.action
if module_args is None:
module_args = self._task.args
self._update_module_args(module_name, module_args, task_vars, ignore_unknown_opts=ignore_unknown_opts)
remove_async_dir = None
if wrap_async or self._task.async_val:
async_dir = self.get_shell_option('async_dir', default="~/.ansible_async")
remove_async_dir = len(self._task.environment)
self._task.environment.append({"ANSIBLE_ASYNC_DIR": async_dir})
(module_style, shebang, module_data, module_path) = self._configure_module(module_name=module_name, module_args=module_args, task_vars=task_vars)
display.vvv("Using module file %s" % module_path)
if not shebang and module_style != 'binary':
raise AnsibleError("module (%s) is missing interpreter line" % module_name)
self._used_interpreter = shebang
remote_module_path = None
if not self._is_pipelining_enabled(module_style, wrap_async):
if tmpdir is None:
self._make_tmp_path()
tmpdir = self._connection._shell.tmpdir
remote_module_filename = self._connection._shell.get_remote_filename(module_path)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
remote_module_path = self._connection._shell.join_path(tmpdir, 'AnsiballZ_%s' % remote_module_filename)
args_file_path = None
if module_style in ('old', 'non_native_want_json', 'binary'):
args_file_path = self._connection._shell.join_path(tmpdir, 'args')
if remote_module_path or module_style != 'new':
display.debug("transferring module to remote %s" % remote_module_path)
if module_style == 'binary':
self._transfer_file(module_path, remote_module_path)
else:
self._transfer_data(remote_module_path, module_data)
if module_style == 'old':
args_data = ""
for k, v in module_args.items():
args_data += '%s=%s ' % (k, shlex.quote(text_type(v)))
self._transfer_data(args_file_path, args_data)
elif module_style in ('non_native_want_json', 'binary'):
self._transfer_data(args_file_path, json.dumps(module_args))
display.debug("done transferring module to remote")
environment_string = self._compute_environment_string()
if remove_async_dir is not None:
del self._task.environment[remove_async_dir]
remote_files = []
if tmpdir and remote_module_path:
remote_files = [tmpdir, remote_module_path]
if args_file_path:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
remote_files.append(args_file_path)
sudoable = True
in_data = None
cmd = ""
if wrap_async and not self._connection.always_pipeline_modules:
(async_module_style, shebang, async_module_data, async_module_path) = self._configure_module(
module_name='ansible.legacy.async_wrapper', module_args=dict(), task_vars=task_vars)
async_module_remote_filename = self._connection._shell.get_remote_filename(async_module_path)
remote_async_module_path = self._connection._shell.join_path(tmpdir, async_module_remote_filename)
self._transfer_data(remote_async_module_path, async_module_data)
remote_files.append(remote_async_module_path)
async_limit = self._task.async_val
async_jid = f'j{random.randint(0, 999999999999)}'
interpreter = shebang.replace('#!', '').strip()
async_cmd = [interpreter, remote_async_module_path, async_jid, async_limit, remote_module_path]
if environment_string:
async_cmd.insert(0, environment_string)
if args_file_path:
async_cmd.append(args_file_path)
else:
async_cmd.append('_')
if not self._should_remove_tmp_path(tmpdir):
async_cmd.append("-preserve_tmp")
cmd = " ".join(to_text(x) for x in async_cmd)
else:
if self._is_pipelining_enabled(module_style):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
in_data = module_data
display.vvv("Pipelining is enabled.")
else:
cmd = remote_module_path
cmd = self._connection._shell.build_module_command(environment_string, shebang, cmd, arg_path=args_file_path).strip()
if remote_files:
remote_files = [x for x in remote_files if x]
self._fixup_perms2(remote_files, self._get_remote_user())
res = self._low_level_execute_command(cmd, sudoable=sudoable, in_data=in_data)
data = self._parse_returned_data(res)
if data.pop("_ansible_suppress_tmpdir_delete", False):
self._cleanup_remote_tmp = False
if 'results' in data and (not isinstance(data['results'], Sequence) or isinstance(data['results'], string_types)):
data['ansible_module_results'] = data['results']
del data['results']
display.warning("Found internal 'results' key in module return, renamed to 'ansible_module_results'.")
remove_internal_keys(data)
if wrap_async:
self._connection._shell.tmpdir = None
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
data['changed'] = True
if 'stdout' in data and 'stdout_lines' not in data:
txt = data.get('stdout', None) or u''
data['stdout_lines'] = txt.splitlines()
if 'stderr' in data and 'stderr_lines' not in data:
txt = data.get('stderr', None) or u''
data['stderr_lines'] = txt.splitlines()
if self._discovered_interpreter_key:
if data.get('ansible_facts') is None:
data['ansible_facts'] = {}
data['ansible_facts'][self._discovered_interpreter_key] = self._discovered_interpreter
if self._discovery_warnings:
if data.get('warnings') is None:
data['warnings'] = []
data['warnings'].extend(self._discovery_warnings)
if self._discovery_deprecation_warnings:
if data.get('deprecations') is None:
data['deprecations'] = []
data['deprecations'].extend(self._discovery_deprecation_warnings)
data = wrap_var(data)
display.debug("done with _execute_module (%s, %s)" % (module_name, module_args))
return data
def _parse_returned_data(self, res):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
try:
filtered_output, warnings = _filter_non_json_lines(res.get('stdout', u''), objects_only=True)
for w in warnings:
display.warning(w)
data = json.loads(filtered_output)
if C.MODULE_STRICT_UTF8_RESPONSE and not data.pop('_ansible_trusted_utf8', None):
try:
_validate_utf8_json(data)
except UnicodeEncodeError:
display.deprecated(
f'Module "{self._task.resolved_action or self._task.action}" returned non UTF-8 data in '
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'the JSON response. This will become an error in the future',
version='2.18',
)
data['_ansible_parsed'] = True
except ValueError:
data = dict(failed=True, _ansible_parsed=False)
data['module_stdout'] = res.get('stdout', u'')
if 'stderr' in res:
data['module_stderr'] = res['stderr']
if res['stderr'].startswith(u'Traceback'):
data['exception'] = res['stderr']
if 'exception' not in data and data['module_stdout'].startswith(u'Traceback'):
data['exception'] = data['module_stdout']
data['msg'] = "MODULE FAILURE"
if self._used_interpreter is not None:
interpreter = re.escape(self._used_interpreter.lstrip('!#'))
match = re.compile('%s: (?:No such file or directory|not found)' % interpreter)
if match.search(data['module_stderr']) or match.search(data['module_stdout']):
data['msg'] = "The module failed to execute correctly, you probably need to set the interpreter."
data['msg'] += '\nSee stdout/stderr for the exact error'
if 'rc' in res:
data['rc'] = res['rc']
return data
def _low_level_execute_command(self, cmd, sudoable=True, in_data=None, executable=None, encoding_errors='surrogate_then_replace', chdir=None):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
'''
This is the function which executes the low level shell command, which
may be commands to create/remove directories for temporary files, or to
run the module code or python directly when pipelining.
:kwarg encoding_errors: If the value returned by the command isn't
utf-8 then we have to figure out how to transform it to unicode.
If the value is just going to be displayed to the user (or
discarded) then the default of 'replace' is fine. If the data is
used as a key or is going to be written back out to a file
verbatim, then this won't work. May have to use some sort of
replacement strategy (python3 could use surrogateescape)
:kwarg chdir: cd into this directory before executing the command.
'''
display.debug("_low_level_execute_command(): starting")
if chdir:
display.debug("_low_level_execute_command(): changing cwd to %s for this command" % chdir)
cmd = self._connection._shell.append_command('cd %s' % chdir, cmd)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
if executable:
self._connection._shell.executable = executable
ruser = self._get_remote_user()
buser = self.get_become_option('become_user')
if (sudoable and self._connection.become and
resource_from_fqcr(self._connection.transport) != 'network_cli' and
(C.BECOME_ALLOW_SAME_USER or (buser != ruser or not any((ruser, buser))))):
display.debug("_low_level_execute_command(): using become for this command")
cmd = self._connection.become.build_become_command(cmd, self._connection._shell)
if self._connection.allow_executable:
if executable is None:
executable = self._play_context.executable
cmd = self._connection._shell.append_command(cmd, 'sleep 0')
if executable:
cmd = executable + ' -c ' + shlex.quote(cmd)
display.debug("_low_level_execute_command(): executing: %s" % (cmd,))
if self._connection.transport == 'local':
self._connection.cwd = to_bytes(self._loader.get_basedir(), errors='surrogate_or_strict')
rc, stdout, stderr = self._connection.exec_command(cmd, in_data=in_data, sudoable=sudoable)
if isinstance(stdout, binary_type):
out = to_text(stdout, errors=encoding_errors)
elif not isinstance(stdout, text_type):
out = to_text(b''.join(stdout.readlines()), errors=encoding_errors)
else:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
out = stdout
if isinstance(stderr, binary_type):
err = to_text(stderr, errors=encoding_errors)
elif not isinstance(stderr, text_type):
err = to_text(b''.join(stderr.readlines()), errors=encoding_errors)
else:
err = stderr
if rc is None:
rc = 0
out = self._strip_success_message(out)
display.debug(u"_low_level_execute_command() done: rc=%d, stdout=%s, stderr=%s" % (rc, out, err))
return dict(rc=rc, stdout=out, stdout_lines=out.splitlines(), stderr=err, stderr_lines=err.splitlines())
def _get_diff_data(self, destination, source, task_vars, content, source_file=True):
#
# di
diff = {}
display.debug("Going to peek to see if file has changed permissions")
peek_result = self._execute_module(
module_name='ansible.legacy.file', module_args=dict(path=destination, _diff_peek=True),
task_vars=task_vars, persist_files=True)
if peek_result.get('failed', False):
display.warning(u"Failed to get diff between '%s' and '%s': %s" % (os.path.basename(source), destination, to_text(peek_result.get(u'msg', u''))))
return diff
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
if peek_result.get('rc', 0) == 0:
if peek_result.get('state') in (None, 'absent'):
diff['before'] = u''
elif peek_result.get('appears_binary'):
diff['dst_binary'] = 1
elif peek_result.get('size') and C.MAX_FILE_SIZE_FOR_DIFF > 0 and peek_result['size'] > C.MAX_FILE_SIZE_FOR_DIFF:
diff['dst_larger'] = C.MAX_FILE_SIZE_FOR_DIFF
else:
display.debug(u"Slurping the file %s" % source)
dest_result = self._execute_module(
module_name='ansible.legacy.slurp', module_args=dict(path=destination),
task_vars=task_vars, persist_files=True)
if 'content' in dest_result:
dest_contents = dest_result['content']
if dest_result['encoding'] == u'base64':
dest_contents = base64.b64decode(dest_contents)
else:
raise AnsibleError("unknown encoding in content option, failed: %s" % to_native(dest_result))
diff['before_header'] = destination
diff['before'] = to_text(dest_contents)
if source_file:
st = os.stat(source)
if C.MAX_FILE_SIZE_FOR_DIFF > 0 and st[stat.ST_SIZE] > C.MAX_FILE_SIZE_FOR_DIFF:
diff['src_larger'] = C.MAX_FILE_SIZE_FOR_DIFF
else:
display.debug("Reading local copy of the file %s" % source)
try:
with open(source, 'rb') as src:
src_contents = src.read()
except Exception as e:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,710 |
Configurable sampling/transfer of control-side task context metadata to targets
|
### Summary
We're often asked how to include arbitrary control-side contextual metadata with task invocations, and to include that metadata in target-side task log messages. e.g.: sending an AWX/Controller Job ID to the target hosts on each module invocation that occurred from that job, and logging it in the module-generated syslog/Windows Application Event Log entries for future correlation with the owning job.
I've not seen any consensus on precisely *which* data to include; one person's "critical forensic correlation data" is another's "unacceptable disclosure of sensitive execution detail". Seems like we'd need a generic facility to specify environment vars and/or hostvars to sample on the control host to be included with task invocations (under a reserved dictionary arg), and adjust the module logging APIs to include them.
My initial thought is to define a new core config element (defaulting to none) that allows the user to define a templated expression that would be rendered as part of each task's templating under a host context. The rendered result would be sent to modules as a new reserved internal module var. The module logging APIs would then include this value verbatim, when present. Other module code would also have access to the value, which could be used for anything. The new config would be settable either via ansible.cfg or an envvar, making it easier for AWX/Controller to later provide a mechanism to configure it for jobs using core versions that support it, while older versions would just silently ignore it.
Maybe something like:
```
ANSIBLE_ADDITIONAL_TASK_CONTEXT='{{awx_job_id}}'
```
When this config is non-empty, the defined template would be rendered for each task/host invocation, and its result included in a new `_ansible_additional_task_context` reserved module var. The resulting value, as with any Ansible template expression, could be of arbitrary complexity (eg, returning a data structure instead of just a scalar). The module logging APIs would include the serialized value verbatim in log messages when it is present, eg "ansible_additional_task_context=(whatever the value was)".
### Issue Type
Feature Idea
### Component Name
module invocation and logging
### Additional Information
<!--- Paste example playbooks or commands between quotes below -->
```yaml (paste below)
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81710
|
https://github.com/ansible/ansible/pull/81711
|
4208bdbbcd994251579409ad533b40c9b0543550
|
1dd0d6fad70d7d4f423dac41822da65ff9ec95ef
| 2023-09-18T16:35:01Z |
python
| 2023-11-30T18:12:55Z |
lib/ansible/plugins/action/__init__.py
|
raise AnsibleError("Unexpected error while reading source (%s) for diff: %s " % (source, to_native(e)))
if b"\x00" in src_contents:
diff['src_binary'] = 1
else:
if content:
diff['after_header'] = destination
else:
diff['after_header'] = source
diff['after'] = to_text(src_contents)
else:
display.debug(u"source of file passed in")
diff['after_header'] = u'dynamically generated'
diff['after'] = source
if self._task.no_log:
if 'before' in diff:
diff["before"] = u""
if 'after' in diff:
diff["after"] = u" [[ Diff output has been hidden because 'no_log: true' was specified for this result ]]\n"
return diff
def _find_needle(self, dirname, needle):
'''
find a needle in haystack of paths, optionally using 'dirname' as a subdir.
This will build the ordered list of paths to search and pass them to dwim
to get back the first existing file found.
'''
# dw
path_stack = self._task.get_search_path()
# if
return self._loader.path_dwim_relative_stack(path_stack, dirname, needle)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,965 |
TypeError: join() missing 1 required positional argument: 'a' in ansible-galaxy
|
### Summary
```plaintext
# ansible-galaxy install willshersystems.sshd --force -vvv
ansible-galaxy [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible-galaxy
python version = 3.9.16 (main, Sep 8 2023, 00:00:00) [GCC 11.4.1 20230605 (Red Hat 11.4.1-2)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
No config file found; using defaults
Starting galaxy role install process
Processing role willshersystems.sshd
Opened /root/.ansible/galaxy_token
- downloading role 'sshd', owned by willshersystems
- downloading role from https://github.com/willshersystems/ansible-sshd/archive/v0.21.0.tar.gz
- extracting willshersystems.sshd to /root/.ansible/roles/willshersystems.sshd
[WARNING]: Illegal filename '..': '..' is not allowed
ERROR! Unexpected Exception, this is probably a bug: join() missing 1 required positional argument: 'a'
the full traceback was:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/ansible/cli/__init__.py", line 659, in cli_executor
exit_code = cli.run()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 719, in run
return context.CLIARGS['func']()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 119, in method_wrapper
return wrapped_method(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1370, in execute_install
self._execute_install_role(role_requirements)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1469, in _execute_install_role
installed = role.install()
File "/usr/local/lib/python3.9/site-packages/ansible/galaxy/role.py", line 426, in install
setattr(member, attr, os.path.join(*n_final_parts))
TypeError: join() missing 1 required positional argument: 'a'
```
For some reason, the list `n_final_parts` doesn't contain any entries which makes this call crash:
```python
os.path.join(*n_final_parts)
```
### Issue Type
Bug Report
### Component Name
ansible-galaxy
### Ansible Version
```console
$ ansible --version
ansible [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible
python version = 3.9.16 (main, Feb 23 2023, 00:00:00) [GCC 11.3.1 20221121 (Red Hat 11.3.1-4)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
```
### Configuration
```console
# if using a version older than ansible-core 2.12 you should omit the '-t all'
$ ansible-config dump --only-changed -t all
CONFIG_FILE() = None
EDITOR(env: EDITOR) = vim
PAGER(env: PAGER) = less
```
### OS / Environment
Amazon Linux 2023
### Steps to Reproduce
not applicable
### Expected Results
I expect the ansible role to be installed
### Actual Results
```console
The installation process crashes, as mentioned above.
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81965
|
https://github.com/ansible/ansible/pull/82165
|
b405958f7998efc2e1d03ecf2d22bcd9276b2533
|
3a42a0036875c8cab6a62ab9ea67a365e1dd4781
| 2023-10-13T08:08:47Z |
python
| 2023-11-30T23:05:48Z |
lib/ansible/galaxy/role.py
|
#
#
#
#
#
#
from __future__ import annotations
import errno
import datetime
import functools
import os
import tarfile
import tempfile
from collections.abc import MutableSequence
from shutil import rmtree
from ansible import context
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.galaxy.api import GalaxyAPI
from ansible.galaxy.user_agent import user_agent
from ansible.module_utils.common.text.converters import to_native, to_text
from ansible.module_utils.common.yaml import yaml_dump, yaml_load
from ansible.module_utils.compat.version import LooseVersion
from ansible.module_utils.urls import open_url
from ansible.playbook.role.requirement import RoleRequirement
from ansible.utils.display import Display
display = Display()
@functools.cache
def _check_working_data_filter() -> bool:
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,965 |
TypeError: join() missing 1 required positional argument: 'a' in ansible-galaxy
|
### Summary
```plaintext
# ansible-galaxy install willshersystems.sshd --force -vvv
ansible-galaxy [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible-galaxy
python version = 3.9.16 (main, Sep 8 2023, 00:00:00) [GCC 11.4.1 20230605 (Red Hat 11.4.1-2)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
No config file found; using defaults
Starting galaxy role install process
Processing role willshersystems.sshd
Opened /root/.ansible/galaxy_token
- downloading role 'sshd', owned by willshersystems
- downloading role from https://github.com/willshersystems/ansible-sshd/archive/v0.21.0.tar.gz
- extracting willshersystems.sshd to /root/.ansible/roles/willshersystems.sshd
[WARNING]: Illegal filename '..': '..' is not allowed
ERROR! Unexpected Exception, this is probably a bug: join() missing 1 required positional argument: 'a'
the full traceback was:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/ansible/cli/__init__.py", line 659, in cli_executor
exit_code = cli.run()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 719, in run
return context.CLIARGS['func']()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 119, in method_wrapper
return wrapped_method(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1370, in execute_install
self._execute_install_role(role_requirements)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1469, in _execute_install_role
installed = role.install()
File "/usr/local/lib/python3.9/site-packages/ansible/galaxy/role.py", line 426, in install
setattr(member, attr, os.path.join(*n_final_parts))
TypeError: join() missing 1 required positional argument: 'a'
```
For some reason, the list `n_final_parts` doesn't contain any entries which makes this call crash:
```python
os.path.join(*n_final_parts)
```
### Issue Type
Bug Report
### Component Name
ansible-galaxy
### Ansible Version
```console
$ ansible --version
ansible [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible
python version = 3.9.16 (main, Feb 23 2023, 00:00:00) [GCC 11.3.1 20221121 (Red Hat 11.3.1-4)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
```
### Configuration
```console
# if using a version older than ansible-core 2.12 you should omit the '-t all'
$ ansible-config dump --only-changed -t all
CONFIG_FILE() = None
EDITOR(env: EDITOR) = vim
PAGER(env: PAGER) = less
```
### OS / Environment
Amazon Linux 2023
### Steps to Reproduce
not applicable
### Expected Results
I expect the ansible role to be installed
### Actual Results
```console
The installation process crashes, as mentioned above.
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81965
|
https://github.com/ansible/ansible/pull/82165
|
b405958f7998efc2e1d03ecf2d22bcd9276b2533
|
3a42a0036875c8cab6a62ab9ea67a365e1dd4781
| 2023-10-13T08:08:47Z |
python
| 2023-11-30T23:05:48Z |
lib/ansible/galaxy/role.py
|
"""
Check if tarfile.data_filter implementation is working
for the current Python version or not
"""
ret = False
if hasattr(tarfile, 'data_filter'):
ti = tarfile.TarInfo('docs/README.md')
ti.type = tarfile.SYMTYPE
ti.linkname = '../README.md'
try:
tarfile.data_filter(ti, '/foo')
except tarfile.LinkOutsideDestinationError:
pass
else:
ret = True
return ret
class GalaxyRole(object):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,965 |
TypeError: join() missing 1 required positional argument: 'a' in ansible-galaxy
|
### Summary
```plaintext
# ansible-galaxy install willshersystems.sshd --force -vvv
ansible-galaxy [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible-galaxy
python version = 3.9.16 (main, Sep 8 2023, 00:00:00) [GCC 11.4.1 20230605 (Red Hat 11.4.1-2)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
No config file found; using defaults
Starting galaxy role install process
Processing role willshersystems.sshd
Opened /root/.ansible/galaxy_token
- downloading role 'sshd', owned by willshersystems
- downloading role from https://github.com/willshersystems/ansible-sshd/archive/v0.21.0.tar.gz
- extracting willshersystems.sshd to /root/.ansible/roles/willshersystems.sshd
[WARNING]: Illegal filename '..': '..' is not allowed
ERROR! Unexpected Exception, this is probably a bug: join() missing 1 required positional argument: 'a'
the full traceback was:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/ansible/cli/__init__.py", line 659, in cli_executor
exit_code = cli.run()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 719, in run
return context.CLIARGS['func']()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 119, in method_wrapper
return wrapped_method(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1370, in execute_install
self._execute_install_role(role_requirements)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1469, in _execute_install_role
installed = role.install()
File "/usr/local/lib/python3.9/site-packages/ansible/galaxy/role.py", line 426, in install
setattr(member, attr, os.path.join(*n_final_parts))
TypeError: join() missing 1 required positional argument: 'a'
```
For some reason, the list `n_final_parts` doesn't contain any entries which makes this call crash:
```python
os.path.join(*n_final_parts)
```
### Issue Type
Bug Report
### Component Name
ansible-galaxy
### Ansible Version
```console
$ ansible --version
ansible [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible
python version = 3.9.16 (main, Feb 23 2023, 00:00:00) [GCC 11.3.1 20221121 (Red Hat 11.3.1-4)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
```
### Configuration
```console
# if using a version older than ansible-core 2.12 you should omit the '-t all'
$ ansible-config dump --only-changed -t all
CONFIG_FILE() = None
EDITOR(env: EDITOR) = vim
PAGER(env: PAGER) = less
```
### OS / Environment
Amazon Linux 2023
### Steps to Reproduce
not applicable
### Expected Results
I expect the ansible role to be installed
### Actual Results
```console
The installation process crashes, as mentioned above.
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81965
|
https://github.com/ansible/ansible/pull/82165
|
b405958f7998efc2e1d03ecf2d22bcd9276b2533
|
3a42a0036875c8cab6a62ab9ea67a365e1dd4781
| 2023-10-13T08:08:47Z |
python
| 2023-11-30T23:05:48Z |
lib/ansible/galaxy/role.py
|
SUPPORTED_SCMS = set(['git', 'hg'])
META_MAIN = (os.path.join('meta', 'main.yml'), os.path.join('meta', 'main.yaml'))
META_INSTALL = os.path.join('meta', '.galaxy_install_info')
META_REQUIREMENTS = (os.path.join('meta', 'requirements.yml'), os.path.join('meta', 'requirements.yaml'))
ROLE_DIRS = ('defaults', 'files', 'handlers', 'meta', 'tasks', 'templates', 'vars', 'tests')
def __init__(self, galaxy, api, name, src=None, version=None, scm=None, path=None):
self._metadata = None
self._metadata_dependencies = None
self._requirements = None
self._install_info = None
self._validate_certs = not context.CLIARGS['ignore_certs']
display.debug('Validate TLS certificates: %s' % self._validate_certs)
self.galaxy = galaxy
self._api = api
self.name = name
self.version = version
self.src = src or name
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,965 |
TypeError: join() missing 1 required positional argument: 'a' in ansible-galaxy
|
### Summary
```plaintext
# ansible-galaxy install willshersystems.sshd --force -vvv
ansible-galaxy [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible-galaxy
python version = 3.9.16 (main, Sep 8 2023, 00:00:00) [GCC 11.4.1 20230605 (Red Hat 11.4.1-2)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
No config file found; using defaults
Starting galaxy role install process
Processing role willshersystems.sshd
Opened /root/.ansible/galaxy_token
- downloading role 'sshd', owned by willshersystems
- downloading role from https://github.com/willshersystems/ansible-sshd/archive/v0.21.0.tar.gz
- extracting willshersystems.sshd to /root/.ansible/roles/willshersystems.sshd
[WARNING]: Illegal filename '..': '..' is not allowed
ERROR! Unexpected Exception, this is probably a bug: join() missing 1 required positional argument: 'a'
the full traceback was:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/ansible/cli/__init__.py", line 659, in cli_executor
exit_code = cli.run()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 719, in run
return context.CLIARGS['func']()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 119, in method_wrapper
return wrapped_method(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1370, in execute_install
self._execute_install_role(role_requirements)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1469, in _execute_install_role
installed = role.install()
File "/usr/local/lib/python3.9/site-packages/ansible/galaxy/role.py", line 426, in install
setattr(member, attr, os.path.join(*n_final_parts))
TypeError: join() missing 1 required positional argument: 'a'
```
For some reason, the list `n_final_parts` doesn't contain any entries which makes this call crash:
```python
os.path.join(*n_final_parts)
```
### Issue Type
Bug Report
### Component Name
ansible-galaxy
### Ansible Version
```console
$ ansible --version
ansible [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible
python version = 3.9.16 (main, Feb 23 2023, 00:00:00) [GCC 11.3.1 20221121 (Red Hat 11.3.1-4)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
```
### Configuration
```console
# if using a version older than ansible-core 2.12 you should omit the '-t all'
$ ansible-config dump --only-changed -t all
CONFIG_FILE() = None
EDITOR(env: EDITOR) = vim
PAGER(env: PAGER) = less
```
### OS / Environment
Amazon Linux 2023
### Steps to Reproduce
not applicable
### Expected Results
I expect the ansible role to be installed
### Actual Results
```console
The installation process crashes, as mentioned above.
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81965
|
https://github.com/ansible/ansible/pull/82165
|
b405958f7998efc2e1d03ecf2d22bcd9276b2533
|
3a42a0036875c8cab6a62ab9ea67a365e1dd4781
| 2023-10-13T08:08:47Z |
python
| 2023-11-30T23:05:48Z |
lib/ansible/galaxy/role.py
|
self.download_url = None
self.scm = scm
self.paths = [os.path.join(x, self.name) for x in galaxy.roles_paths]
if path is not None:
if not path.endswith(os.path.join(os.path.sep, self.name)):
path = os.path.join(path, self.name)
else:
#
for meta_main in self.META_MAIN:
if os.path.exists(os.path.join(path, name, meta_main)):
path = os.path.join(path, self.name)
break
self.path = path
else:
self.path = self.paths[0]
def __repr__(self):
"""
Returns "rolename (version)" if version is not null
Returns "rolename" otherwise
"""
if self.version:
return "%s (%s)" % (self.name, self.version)
else:
return self.name
def __eq__(self, other):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,965 |
TypeError: join() missing 1 required positional argument: 'a' in ansible-galaxy
|
### Summary
```plaintext
# ansible-galaxy install willshersystems.sshd --force -vvv
ansible-galaxy [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible-galaxy
python version = 3.9.16 (main, Sep 8 2023, 00:00:00) [GCC 11.4.1 20230605 (Red Hat 11.4.1-2)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
No config file found; using defaults
Starting galaxy role install process
Processing role willshersystems.sshd
Opened /root/.ansible/galaxy_token
- downloading role 'sshd', owned by willshersystems
- downloading role from https://github.com/willshersystems/ansible-sshd/archive/v0.21.0.tar.gz
- extracting willshersystems.sshd to /root/.ansible/roles/willshersystems.sshd
[WARNING]: Illegal filename '..': '..' is not allowed
ERROR! Unexpected Exception, this is probably a bug: join() missing 1 required positional argument: 'a'
the full traceback was:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/ansible/cli/__init__.py", line 659, in cli_executor
exit_code = cli.run()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 719, in run
return context.CLIARGS['func']()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 119, in method_wrapper
return wrapped_method(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1370, in execute_install
self._execute_install_role(role_requirements)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1469, in _execute_install_role
installed = role.install()
File "/usr/local/lib/python3.9/site-packages/ansible/galaxy/role.py", line 426, in install
setattr(member, attr, os.path.join(*n_final_parts))
TypeError: join() missing 1 required positional argument: 'a'
```
For some reason, the list `n_final_parts` doesn't contain any entries which makes this call crash:
```python
os.path.join(*n_final_parts)
```
### Issue Type
Bug Report
### Component Name
ansible-galaxy
### Ansible Version
```console
$ ansible --version
ansible [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible
python version = 3.9.16 (main, Feb 23 2023, 00:00:00) [GCC 11.3.1 20221121 (Red Hat 11.3.1-4)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
```
### Configuration
```console
# if using a version older than ansible-core 2.12 you should omit the '-t all'
$ ansible-config dump --only-changed -t all
CONFIG_FILE() = None
EDITOR(env: EDITOR) = vim
PAGER(env: PAGER) = less
```
### OS / Environment
Amazon Linux 2023
### Steps to Reproduce
not applicable
### Expected Results
I expect the ansible role to be installed
### Actual Results
```console
The installation process crashes, as mentioned above.
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81965
|
https://github.com/ansible/ansible/pull/82165
|
b405958f7998efc2e1d03ecf2d22bcd9276b2533
|
3a42a0036875c8cab6a62ab9ea67a365e1dd4781
| 2023-10-13T08:08:47Z |
python
| 2023-11-30T23:05:48Z |
lib/ansible/galaxy/role.py
|
return self.name == other.name
@property
def api(self):
if not isinstance(self._api, GalaxyAPI):
return self._api.api
return self._api
@property
def metadata(self):
"""
Returns role metadata
"""
if self._metadata is None:
for path in self.paths:
for meta_main in self.META_MAIN:
meta_path = os.path.join(path, meta_main)
if os.path.isfile(meta_path):
try:
with open(meta_path, 'r') as f:
self._metadata = yaml_load(f)
except Exception:
display.vvvvv("Unable to load metadata for %s" % self.name)
return False
break
return self._metadata
@property
def metadata_dependencies(self):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,965 |
TypeError: join() missing 1 required positional argument: 'a' in ansible-galaxy
|
### Summary
```plaintext
# ansible-galaxy install willshersystems.sshd --force -vvv
ansible-galaxy [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible-galaxy
python version = 3.9.16 (main, Sep 8 2023, 00:00:00) [GCC 11.4.1 20230605 (Red Hat 11.4.1-2)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
No config file found; using defaults
Starting galaxy role install process
Processing role willshersystems.sshd
Opened /root/.ansible/galaxy_token
- downloading role 'sshd', owned by willshersystems
- downloading role from https://github.com/willshersystems/ansible-sshd/archive/v0.21.0.tar.gz
- extracting willshersystems.sshd to /root/.ansible/roles/willshersystems.sshd
[WARNING]: Illegal filename '..': '..' is not allowed
ERROR! Unexpected Exception, this is probably a bug: join() missing 1 required positional argument: 'a'
the full traceback was:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/ansible/cli/__init__.py", line 659, in cli_executor
exit_code = cli.run()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 719, in run
return context.CLIARGS['func']()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 119, in method_wrapper
return wrapped_method(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1370, in execute_install
self._execute_install_role(role_requirements)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1469, in _execute_install_role
installed = role.install()
File "/usr/local/lib/python3.9/site-packages/ansible/galaxy/role.py", line 426, in install
setattr(member, attr, os.path.join(*n_final_parts))
TypeError: join() missing 1 required positional argument: 'a'
```
For some reason, the list `n_final_parts` doesn't contain any entries which makes this call crash:
```python
os.path.join(*n_final_parts)
```
### Issue Type
Bug Report
### Component Name
ansible-galaxy
### Ansible Version
```console
$ ansible --version
ansible [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible
python version = 3.9.16 (main, Feb 23 2023, 00:00:00) [GCC 11.3.1 20221121 (Red Hat 11.3.1-4)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
```
### Configuration
```console
# if using a version older than ansible-core 2.12 you should omit the '-t all'
$ ansible-config dump --only-changed -t all
CONFIG_FILE() = None
EDITOR(env: EDITOR) = vim
PAGER(env: PAGER) = less
```
### OS / Environment
Amazon Linux 2023
### Steps to Reproduce
not applicable
### Expected Results
I expect the ansible role to be installed
### Actual Results
```console
The installation process crashes, as mentioned above.
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81965
|
https://github.com/ansible/ansible/pull/82165
|
b405958f7998efc2e1d03ecf2d22bcd9276b2533
|
3a42a0036875c8cab6a62ab9ea67a365e1dd4781
| 2023-10-13T08:08:47Z |
python
| 2023-11-30T23:05:48Z |
lib/ansible/galaxy/role.py
|
"""
Returns a list of dependencies from role metadata
"""
if self._metadata_dependencies is None:
self._metadata_dependencies = []
if self.metadata is not None:
self._metadata_dependencies = self.metadata.get('dependencies') or []
if not isinstance(self._metadata_dependencies, MutableSequence):
raise AnsibleParserError(
f"Expected role dependencies to be a list. Role {self} has meta/main.yml with dependencies {self._metadata_dependencies}"
)
return self._metadata_dependencies
@property
def install_info(self):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,965 |
TypeError: join() missing 1 required positional argument: 'a' in ansible-galaxy
|
### Summary
```plaintext
# ansible-galaxy install willshersystems.sshd --force -vvv
ansible-galaxy [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible-galaxy
python version = 3.9.16 (main, Sep 8 2023, 00:00:00) [GCC 11.4.1 20230605 (Red Hat 11.4.1-2)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
No config file found; using defaults
Starting galaxy role install process
Processing role willshersystems.sshd
Opened /root/.ansible/galaxy_token
- downloading role 'sshd', owned by willshersystems
- downloading role from https://github.com/willshersystems/ansible-sshd/archive/v0.21.0.tar.gz
- extracting willshersystems.sshd to /root/.ansible/roles/willshersystems.sshd
[WARNING]: Illegal filename '..': '..' is not allowed
ERROR! Unexpected Exception, this is probably a bug: join() missing 1 required positional argument: 'a'
the full traceback was:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/ansible/cli/__init__.py", line 659, in cli_executor
exit_code = cli.run()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 719, in run
return context.CLIARGS['func']()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 119, in method_wrapper
return wrapped_method(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1370, in execute_install
self._execute_install_role(role_requirements)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1469, in _execute_install_role
installed = role.install()
File "/usr/local/lib/python3.9/site-packages/ansible/galaxy/role.py", line 426, in install
setattr(member, attr, os.path.join(*n_final_parts))
TypeError: join() missing 1 required positional argument: 'a'
```
For some reason, the list `n_final_parts` doesn't contain any entries which makes this call crash:
```python
os.path.join(*n_final_parts)
```
### Issue Type
Bug Report
### Component Name
ansible-galaxy
### Ansible Version
```console
$ ansible --version
ansible [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible
python version = 3.9.16 (main, Feb 23 2023, 00:00:00) [GCC 11.3.1 20221121 (Red Hat 11.3.1-4)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
```
### Configuration
```console
# if using a version older than ansible-core 2.12 you should omit the '-t all'
$ ansible-config dump --only-changed -t all
CONFIG_FILE() = None
EDITOR(env: EDITOR) = vim
PAGER(env: PAGER) = less
```
### OS / Environment
Amazon Linux 2023
### Steps to Reproduce
not applicable
### Expected Results
I expect the ansible role to be installed
### Actual Results
```console
The installation process crashes, as mentioned above.
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81965
|
https://github.com/ansible/ansible/pull/82165
|
b405958f7998efc2e1d03ecf2d22bcd9276b2533
|
3a42a0036875c8cab6a62ab9ea67a365e1dd4781
| 2023-10-13T08:08:47Z |
python
| 2023-11-30T23:05:48Z |
lib/ansible/galaxy/role.py
|
"""
Returns role install info
"""
if self._install_info is None:
info_path = os.path.join(self.path, self.META_INSTALL)
if os.path.isfile(info_path):
try:
f = open(info_path, 'r')
self._install_info = yaml_load(f)
except Exception:
display.vvvvv("Unable to load Galaxy install info for %s" % self.name)
return False
finally:
f.close()
return self._install_info
@property
def _exists(self):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,965 |
TypeError: join() missing 1 required positional argument: 'a' in ansible-galaxy
|
### Summary
```plaintext
# ansible-galaxy install willshersystems.sshd --force -vvv
ansible-galaxy [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible-galaxy
python version = 3.9.16 (main, Sep 8 2023, 00:00:00) [GCC 11.4.1 20230605 (Red Hat 11.4.1-2)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
No config file found; using defaults
Starting galaxy role install process
Processing role willshersystems.sshd
Opened /root/.ansible/galaxy_token
- downloading role 'sshd', owned by willshersystems
- downloading role from https://github.com/willshersystems/ansible-sshd/archive/v0.21.0.tar.gz
- extracting willshersystems.sshd to /root/.ansible/roles/willshersystems.sshd
[WARNING]: Illegal filename '..': '..' is not allowed
ERROR! Unexpected Exception, this is probably a bug: join() missing 1 required positional argument: 'a'
the full traceback was:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/ansible/cli/__init__.py", line 659, in cli_executor
exit_code = cli.run()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 719, in run
return context.CLIARGS['func']()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 119, in method_wrapper
return wrapped_method(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1370, in execute_install
self._execute_install_role(role_requirements)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1469, in _execute_install_role
installed = role.install()
File "/usr/local/lib/python3.9/site-packages/ansible/galaxy/role.py", line 426, in install
setattr(member, attr, os.path.join(*n_final_parts))
TypeError: join() missing 1 required positional argument: 'a'
```
For some reason, the list `n_final_parts` doesn't contain any entries which makes this call crash:
```python
os.path.join(*n_final_parts)
```
### Issue Type
Bug Report
### Component Name
ansible-galaxy
### Ansible Version
```console
$ ansible --version
ansible [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible
python version = 3.9.16 (main, Feb 23 2023, 00:00:00) [GCC 11.3.1 20221121 (Red Hat 11.3.1-4)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
```
### Configuration
```console
# if using a version older than ansible-core 2.12 you should omit the '-t all'
$ ansible-config dump --only-changed -t all
CONFIG_FILE() = None
EDITOR(env: EDITOR) = vim
PAGER(env: PAGER) = less
```
### OS / Environment
Amazon Linux 2023
### Steps to Reproduce
not applicable
### Expected Results
I expect the ansible role to be installed
### Actual Results
```console
The installation process crashes, as mentioned above.
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81965
|
https://github.com/ansible/ansible/pull/82165
|
b405958f7998efc2e1d03ecf2d22bcd9276b2533
|
3a42a0036875c8cab6a62ab9ea67a365e1dd4781
| 2023-10-13T08:08:47Z |
python
| 2023-11-30T23:05:48Z |
lib/ansible/galaxy/role.py
|
for path in self.paths:
if os.path.isdir(path):
return True
return False
def _write_galaxy_install_info(self):
"""
Writes a YAML-formatted file to the role's meta/ directory
(named .galaxy_install_info) which contains some information
we can use later for commands like 'list' and 'info'.
"""
info = dict(
version=self.version,
install_date=datetime.datetime.now(datetime.timezone.utc).strftime("%c"),
)
if not os.path.exists(os.path.join(self.path, 'meta')):
os.makedirs(os.path.join(self.path, 'meta'))
info_path = os.path.join(self.path, self.META_INSTALL)
with open(info_path, 'w+') as f:
try:
self._install_info = yaml_dump(info, f)
except Exception:
return False
return True
def remove(self):
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 81,965 |
TypeError: join() missing 1 required positional argument: 'a' in ansible-galaxy
|
### Summary
```plaintext
# ansible-galaxy install willshersystems.sshd --force -vvv
ansible-galaxy [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible-galaxy
python version = 3.9.16 (main, Sep 8 2023, 00:00:00) [GCC 11.4.1 20230605 (Red Hat 11.4.1-2)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
No config file found; using defaults
Starting galaxy role install process
Processing role willshersystems.sshd
Opened /root/.ansible/galaxy_token
- downloading role 'sshd', owned by willshersystems
- downloading role from https://github.com/willshersystems/ansible-sshd/archive/v0.21.0.tar.gz
- extracting willshersystems.sshd to /root/.ansible/roles/willshersystems.sshd
[WARNING]: Illegal filename '..': '..' is not allowed
ERROR! Unexpected Exception, this is probably a bug: join() missing 1 required positional argument: 'a'
the full traceback was:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/ansible/cli/__init__.py", line 659, in cli_executor
exit_code = cli.run()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 719, in run
return context.CLIARGS['func']()
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 119, in method_wrapper
return wrapped_method(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1370, in execute_install
self._execute_install_role(role_requirements)
File "/usr/local/lib/python3.9/site-packages/ansible/cli/galaxy.py", line 1469, in _execute_install_role
installed = role.install()
File "/usr/local/lib/python3.9/site-packages/ansible/galaxy/role.py", line 426, in install
setattr(member, attr, os.path.join(*n_final_parts))
TypeError: join() missing 1 required positional argument: 'a'
```
For some reason, the list `n_final_parts` doesn't contain any entries which makes this call crash:
```python
os.path.join(*n_final_parts)
```
### Issue Type
Bug Report
### Component Name
ansible-galaxy
### Ansible Version
```console
$ ansible --version
ansible [core 2.15.5]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible
python version = 3.9.16 (main, Feb 23 2023, 00:00:00) [GCC 11.3.1 20221121 (Red Hat 11.3.1-4)] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True
```
### Configuration
```console
# if using a version older than ansible-core 2.12 you should omit the '-t all'
$ ansible-config dump --only-changed -t all
CONFIG_FILE() = None
EDITOR(env: EDITOR) = vim
PAGER(env: PAGER) = less
```
### OS / Environment
Amazon Linux 2023
### Steps to Reproduce
not applicable
### Expected Results
I expect the ansible role to be installed
### Actual Results
```console
The installation process crashes, as mentioned above.
```
### Code of Conduct
- [X] I agree to follow the Ansible Code of Conduct
|
https://github.com/ansible/ansible/issues/81965
|
https://github.com/ansible/ansible/pull/82165
|
b405958f7998efc2e1d03ecf2d22bcd9276b2533
|
3a42a0036875c8cab6a62ab9ea67a365e1dd4781
| 2023-10-13T08:08:47Z |
python
| 2023-11-30T23:05:48Z |
lib/ansible/galaxy/role.py
|
"""
Removes the specified role from the roles path.
There is a sanity check to make sure there's a meta/main.yml file at this
path so the user doesn't blow away random directories.
"""
if self.metadata:
try:
rmtree(self.path)
return True
except Exception:
pass
return False
def fetch(self, role_data):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.