python - Get value of a fact set with 'set_fact' inside a callback plugin -
ansible 2.3
i have callback plugin notifies external service when playbook finished. during play, callback plugin collects different information play variables , error messages, sent http request. example:
{ "status": 1, "activity": 270, "error": "task xyz failed message: failure message", "files": [ "a.txt", "b.cfg" ] }
some of information comes variables set during play itself, relevant play: path file, list of changed resources, etc.
right i'm doing particularly ugly collect need based on task names:
def v2_runner_on_ok(self, result): if result._task.action == 'archive': if result._task.name == 'create archive foo': self.body['path'] = result._result['path'] if result._task.action == 'ec2': if result._task.name == 'start instance bar': self.body['ec2_id'] = result._result['id'] # every task generates "interesting" info
obviously doesn't scale , breaks if task name changes.
to keep generic i've been thinking agreeing on fact name, add_to_body
, added body
dictionary whenever exists. approach because it's particularly easy register couple of variables during play , use them assemble fact @ end of play. example:
--- - name: demo play hosts: localhost gather_facts: false tasks: - name: create temporary file 1 tempfile: path: '/tmp' register: reg_tmp_1 - name: create temporary file 2 tempfile: path: '/tmp' register: reg_tmp_2 - name: set add_to_body fact set_fact: add_to_body: "{{ { 'reg_tmp_1': reg_tmp_1.path, 'reg_tmp_2': reg_tmp_2.path } }}" - debug: var=add_to_body
however can't find way access value of fact after set_fact
action, neither looking @ result
object nor trying access hostvars
current host (which apparently not possible inside callback plugin).
what suggest work around limitation?
hmm, mix things in here.
if want call api in v2_runner_on_ok
after each task, should handle add_to_body
in task context.
in example set add_to_body
after several tasks – way you'd better write action plugin (e.g. send_to_my_service
) , call instead of set_fact
required parameters.
here's example how can use add_to_body
in task context:
--- - hosts: localhost gather_facts: no tasks: - command: echo hello world vars: add_to_body: - path - file: dest: /tmp/zzz state: touch vars: add_to_body: - dest
callback:
def v2_runner_on_ok(self, result): if 'add_to_body' in result._task.vars: res = dict() in result._task.vars['add_to_body']: if in result._result: res[i] = result._result[i] else: display.warning('add_to_body: asked add "{}", property not found'.format(i)) display.v(res)
Comments
Post a Comment