json строка преобразуется в формате python в playbook - PullRequest
0 голосов
/ 19 марта 2020

Я хочу запустить несколько python сценариев, возвращающих json на хостах и, наконец, получить сводку json:

{'server1': {script1_label: { stdout }, 
             script2_label: { stdout }
            },
 'server2': {script1_label: { stdout }, 
             script2_label: { stdout }
            },
}

stdout - это вывод json каждого python сценария.

Моя книга воспроизведения:

задач:

- name: Execute Python Script
  shell: "python /srv/sources/{{ item.script }}"
  async: 30000
  poll: 10
  ignore_errors: yes
  failed_when: false
  register: "result"
  loop:
    - { script: 'checks_lines.py', variable: 'checks_lines' }
    - { script: 'checks_permissions.py', variable: 'checks_permissions' }

- debug:
    msg: "{ {% for host in ansible_play_hosts %}
                 {{ hostvars[host]['result']['results'] }},
             {% endfor %} }"
  run_once: true

- debug:
    msg: "{ {% for host in ansible_play_hosts %}
                 {{ hostvars[host]['result']['results'][0]['stdout'] }},
             {% endfor %} }"
  run_once: true

- debug:
    msg: "{ {% for host in ansible_play_hosts %}
              \"{{ host }}\":
              {
              {% for cmd in hostvars[host]['result']['results'] %}    
                  \"{{ cmd['item']['variable'] }}\" : {{ cmd['stdout'] }} ,
              {% endfor %}
              },
            {% endfor %} }"
  run_once: true

первое возвращаемое задание:

{  [{'_ansible_parsed': True, 'stderr_lines': [], u'cmd': u'python /srv/sources/claranet/checks_lines.py', u'end': u'2020-03-19 11:18:11.784980', '_ansible_no_log': False, u'ansible_job_id': u'668039752167.115804', u'stdout': u'{"/etc/sysctl.conf": {"kernel.exec-shield": {"present": false, "value": []}}, "/etc/ssh/sshd_config": {"ClientAliveInterval": {"pres
ent": true, "value": ["0"]}, "ClientAliveCountMax": {"present": true, "value": ["3"]}}}', '_ansible_item_result': True, u'changed': True, u'start': u'2020-03-19 11:18:11.755788', u'invocation': {u'module_args': {u'warn': True, u'executable': None, u'_uses_shell': True, u'_raw_params': u'python /srv/sources/claranet/checks_lines.py', u'removes': None, u'argv'
: None, u'creates': None, u'chdir': None, u'stdin': None}}, 'failed': False, u'finished': 1, 'item': {u'variable': u'checks_lines', u'script': u'checks_lines.py'}, u'rc': 0, u'delta': u'0:00:00.029192', 'stdout_lines': [u'{"/etc/sysctl.conf": {"kernel.exec-shield": {"present": false, "value": []}}, "/etc/ssh/sshd_config": {"ClientAliveInterval": {"present": 
true, "value": ["0"]}, "ClientAliveCountMax": {"present": true, "value": ["3"]}}}'], 'failed_when_result': False, u'stderr': u'', '_ansible_ignore_errors': True, '_ansible_item_label': {u'variable': u'checks_lines', u'script': u'checks_lines.py'}}, {'_ansible_parsed': True, 'stderr_lines': [], u'cmd': u'python /srv/sources/claranet/checks_permissions.py', u'
end': u'2020-03-19 11:18:23.654521', '_ansible_no_log': False, u'ansible_job_id': u'257312332479.116038', u'stdout': u'{"/etc/fstab": "644", "/etc/crontab": "644"}', '_ansible_item_result': True, u'changed': True, u'start': u'2020-03-19 11:18:23.635674', u'invocation': {u'module_args': {u'warn': True, u'executable': None, u'_uses_shell': True, u'_raw_params'
: u'python /srv/sources/claranet/checks_permissions.py', u'removes': None, u'argv': None, u'creates': None, u'chdir': None, u'stdin': None}}, 'failed': False, u'finished': 1, 'item': {u'variable': u'checks_permissions', u'script': u'checks_permissions.py'}, u'rc': 0, u'delta': u'0:00:00.018847', 'stdout_lines': [u'{"/etc/fstab": "644", "/etc/crontab": "644"}
'], 'failed_when_result': False, u'stderr': u'', '_ansible_ignore_errors': True, '_ansible_item_label': {u'variable': u'checks_permissions', u'script': u'checks_permissions.py'}}],  }

ОК, стандартный вывод - строка json ( python вывод сценария).

Моя вторая задача отладки возвращает только один стандартный вывод:

{  {"/etc/sysctl.conf": {"kernel.exec-shield": {"present": false, "value": []}}, "/etc/ssh/sshd_config": {"ClientAliveInterval": {"present": true, "value": ["0"]}, "ClientAliveCountMax": {"present": true, "value": ["3"]}}},  }

ОК, это уже json строка

Моя третья задача вернуть сводку для всех серверов:

{'z98sl080pstemp9.cly.dtc3.cf.saint-gobain.net': {'checks_permissions': {'/etc/fstab': u'644', '/etc/crontab': u'644'}, 'checks_lines': {'/etc/sysctl.conf': {'kernel.exec-shield': {'present': False, 'value': []}}, '/etc/ssh/sshd_config': {'ClientAliveInterval': {'present': True, 'value': [u'0']}, 'ClientAliveCountMax': {'present': True, 'value': [u'3']}}}}}

Стандартный вывод - это не строка json, а формат python:

  • ["3"] -> [u '3']
  • true -> True
  • Et c ....

Почему моя строка json преобразована в формат python ?

Как сохранить строку json?

Есть ли лучшее, чтобы построить финал json?

Спасибо.

Дэвид.

1 Ответ

0 голосов
/ 20 марта 2020

Я использовал временную переменную (set_facts). И это работает ....

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...