如果我的情况失败,如何实现从某个位置删除文件。
- set_fact:
mysql_dump_file: "{{ db_name }}_backup-{{ ansible_date_time.iso8601 }}.sql"
- name: create backup of the EMS database
shell: " mysqldump --single-transaction --triggers --routines --events --hex-blob --complete-insert -h {{ db_name }} -u {{ db_user }} -p{{ db_password }} {{ db_name }} > {{ vars.inventory_dir }}/../{{ mysql_dump_file }}"
register: db_backup_done
- name: Fail play if database backup fail
fail:
msg: 'The database {{ db_name }} backup fail.'
when: "db_backup_done.rc != 0"
如果播放失败,我只想删除“mysql_dump_file”。
答案 0 :(得分:2)
您还可以使用ansible块。这使你更清楚自己在做什么。
-block:
- set_fact:
mysql_dump_file: "{{ db_name }}_backup-{{ ansible_date_time.iso8601 }}.sql"
- name: create backup of the EMS database
shell: " mysqldump --single-transaction --triggers --routines --events --hex-blob --complete-insert -h {{ db_name }} -u {{ db_user }} -p{{ db_password }} {{ db_name }} > {{ vars.inventory_dir }}/../{{ mysql_dump_file }}"
register: db_backup_done
- name: Fail play if database backup fail
fail:
msg: 'The database {{ db_name }} backup fail.'
when: "db_backup_done.rc != 0"
rescue:
- name: Remove the mysql_dump_file if db backup failed
file: path={{ mysql_dump_file }} state=absent
答案 1 :(得分:1)
您可以在“创建EMS数据库备份”任务中添加“ignore_errors: yes
”,以便在命令失败并且您可以使用相同的“db_backup_done.rc != 0
”条件时播放不会失败删除备份文件。
- name: create backup of the EMS database
shell: " mysqldump --single-transaction --triggers --routines --events --hex-blob --complete-insert -h {{ db_name }} -u {{ db_user }} -p{{ db_password }} {{ db_name }} > {{ vars.inventory_dir }}/../{{ mysql_dump_file }}"
register: db_backup_done
ignore_errors: yes
- name: Remove the mysql_dump_file if db backup failed
file: path={{ mysql_dump_file }} state=absent
when: "db_backup_done.rc != 0"