我正在尝试在ansible playbook中运行命令任务,如果失败,我想运行救援部分。如果命令失败(退出状态!= 0)并且stderr输出不包含某个字符串,我希望失败状态是这样的
- block:
- name: some command
command: "command {{ my_var }}"
register: command_status
failed_when: command_status.rc != 0 and "Some text" not in command_status.stderr
changed_when: false
rescue:
- name: error occurred. Rolling back
command: rescue-command
上面的问题是,如果上面没有定义变量my_var
,命令将失败(带有the field 'args' has an invalid value, which appears to include a variable that is undefined
之类的消息,救援部分将运行,这是不可取的。有没有避免Ansible考虑Ansible特定错误与来自剧中实际命令的错误?
我希望rc
返回值只能特定于命令,但似乎并非如此。
我正在运行Ansible 2.3
答案 0 :(得分:1)
不直接区分错误的来源,而是更多地针对您的用例进行黑客攻击:
您可以将function clear_out_potential_duplicate_events( $post_id, $post = null, $update = false ) {
if ( DOING_CRON === false ) {
return false;
}
if ( $update === true ) {
return false;
}
global $wpdb;
$wptexturize = remove_filter( 'the_title', 'wptexturize' );
$title_check = get_the_title( $post_id );
if ( $wptexturize ) {
add_filter( 'the_title', 'wptexturize' );
}
$start_date_check = get_post_meta( $post_id, '_EventStartDate', true );
$end_date_check = get_post_meta( $post_id, '_EventEndDate', true );
$results = $wpdb->get_results( "SELECT ID FROM `wp_posts` JOIN `wp_postmeta` ON wp_posts.ID = wp_postmeta.post_id WHERE wp_postmeta.meta_value = '$start_date_check' AND wp_postmeta.meta_value = '$end_date_check' AND wp_posts.post_title = '$title_check'" );
if ( ! empty( $results ) ) {
wp_delete_post( $post_id );
}
}
的支票添加到救援部分。如果模块失败,则不会定义变量command_status.cmd
,因此救援任务将不会运行:
command_status.cmd
答案 1 :(得分:0)
如果出现意外错误,我会使用显式fail
扩展@ techraf的答案,否则Ansible将继续执行任务,就像没有发生任何不良事件一样。
- block:
- name: some command
command: "command {{ my_var }}"
register: command_status
failed_when: command_status.rc != 0 and "Some text" not in command_status.stderr
changed_when: false
rescue:
- fail:
msg: Unexpected error occurred "{{ command_status.msg }}"
when: command_status.failed_when_result is undefined
- name: Expected error occurred. Rolling back
command: rescue-command
如果错误是意外的,这将导致主机失败(因为failed_when_result
已定义,如果failed_when
的任务已完成);如果出现错误(由于failed_when
语句命令失败,将应用rescue-command。