![ansible logrotate 与 postrorate 脚本的问题](https://linux22.com/image/783771/ansible%20logrotate%20%E4%B8%8E%20postrorate%20%E8%84%9A%E6%9C%AC%E7%9A%84%E9%97%AE%E9%A2%98.png)
以下是我的 ansible 角色 > defaults/main.yaml
$cat roles/logrotate/defaults/main.yml
logrotate_conf_dir: "/etc/logrotate.d/"
logrotate_scripts:
- name: test
log_dir: '/var/log/test'
log_extension: 'log'
options:
- rotate 7
- weekly
- size 10M
- missingok
- compress
- create 0644 test test
scripts:
postrotate: "echo test >> /var/log/test.log"
我的 task/main.yaml 有
$ cat roles/logrotate/tasks/main.yaml
# tasks file for nginx
- name: Setup logrotate scripts
template:
src: logrotate.d.j2
dest: "{{ logrotate_conf_dir }}{{ item.name }}"
with_items: "{{ logrotate_scripts }}"
when: logrotate_scripts is defined
运行这个简单的剧本时出现以下错误:
任务 [logrotate:设置 logrotate 脚本] **************************************************************************************************************** 任务执行期间发生异常。要查看完整回溯,请使用 -vvv。错误是:ansible.errors.AnsibleUndefinedVariable:“dict object”没有属性“iteritems”失败:[10.20.5.72](item = {'name':'test','log_dir':'/ var / log / test','log_extension':'log','options':['rotate 7','weekly','size 10M','missingok','compress','create 0644 test test'],'scripts':{'postrotate':'echo test >> /var/log/test.log'}}) => {“ansible_loop_var”:“item”,“changed”:false,“item”:{“log_dir”:“/ var / log / test”,“log_extension”:“log”,“name”:“test”,“options”:[“rotate 7”,“weekly”,“size 10M”、“missingok”、“compress”、“create 0644 test test”],“scripts”: {“postrotate”: “echo test >> /var/log/test.log”}},“msg”: “AnsibleUndefinedVariable:‘dict object’没有属性‘iteritems’”}
答案1
在模板中,修复迭代。例如,
{% for k,v in item.scripts.items() %}
完整测试剧本的示例
shell> cat pb.yml
- hosts: localhost
vars:
logrotate_conf_dir: "/etc/logrotate.d/"
logrotate_scripts:
- name: test
log_dir: '/var/log/test'
log_extension: 'log'
options:
- rotate 7
- weekly
- size 10M
- missingok
- compress
- create 0644 test test
scripts:
postrotate: "echo test >> /var/log/test.log"
tasks:
- name: Setup logrotate scripts
template:
src: logrotate.d.j2
dest: "{{ logrotate_conf_dir }}{{ item.name }}"
loop: "{{ logrotate_scripts|d([]) }}"
shell> cat logrotate.d.j2
{{ item.log_dir }}/{{ item.name }}.{{ item.log_extension }}
{
{% for option in item.options %}
{{ option }}
{% endfor %}
{% for k,v in item.scripts.items() %}
{{ k }}
{{ v }}
endscript
{% endfor %}
}
给出(--check--diff)
+/var/log/test/test.log
+{
+ rotate 7
+ weekly
+ size 10M
+ missingok
+ compress
+ create 0644 test test
+ postrotate
+ echo test >> /var/log/test.log
+ endscript
+}