Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

How to set cronjobs with different schedule time for hosts from python dict using ansible?

I have a ansible task which runs a python script to get the cron schedule time as follows

- name: check the expiry of node certificates using python script
  shell: python /opt/cron_exp.py
  register: cron_schedule
  when: inventory_hostname in groups['kubemaster']

The output of the script is a dictionary (print in python) which is captured by the register cron_schedule as follows:

- debug:
    msg: "{{cron_schedule}}"
  when: inventory_hostname in groups['kubemaster']


MSG:

{'stderr_lines': [], u'cmd': u'python /opt/cron_exp.py', u'end': u'2021-01-06 03:59:45.980785', u'stdout': u"{u'node1': {'month': 12, 'hour': 11, 'minute': 2, 'day': 8}, u'node3': {'month': 12, 'hour': 11, 'minute': 2, 'day': 8}, u'node2': {'month': 12, 'hour': 11, 'minute': 7, 'day': 8}, u'master': {'month': 12, 'hour': 11, 'minute': 2, 'day': 8}}", u'changed': True, u'rc': 0, 'failed': False, u'stderr': u'', u'delta': u'0:00:00.632724', 'stdout_lines': [u"{u'node1': {'month': 12, 'hour': 11, 'minute': 2, 'day': 8}, u'node3': {'month': 12, 'hour': 11, 'minute': 2, 'day': 8}, u'node2': {'month': 12, 'hour': 11, 'minute': 7, 'day': 8}, u'master': {'month': 12, 'hour': 11, 'minute': 2, 'day': 8}}"], u'start': u'2021-01-06 03:59:45.348061'}


Here the ansible hosts are master, node1, node2... I want to set the cronjob in all the hosts by referring to the python dictionary output key with hostnames and respective values having month, hour , minute and day. To achieve this, I have tried to use loop for the dict as follows:

- name: Set a cronjob 
  cron:
    name: "origin node restart cron"
    minute: "{{ item.value.minute }}"
    hour: "{{ item.value.hour }}"
    day: "{{ item.value.day }}"
    month: "{{ item.value.month }}"
    job: 'service origin-node restart'
  when: inventory_hostname in groups[item.key]
  loop: "{{ lookup('dict', cron_schedule.stdout) }}"

But its throwing the error as follows:

fatal: [master]: FAILED! => {}

MSG:

An unhandled exception occurred while running the lookup plugin 'dict'. Error was a <class 'ansible.errors.AnsibleError'>, original message: with_dict expects a dict

I tried with_dict instead of loop as suggested here Ansible with_dict expects a dict but no luck

Please help me to debug this or is there any alternative that I can try.

Note: Ansible version: 2.9.5


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...