Ansible 优化playbook,使其与shell模块等幂

Ansible 优化playbook,使其与shell模块等幂,ansible,ansible-playbook,idempotent,Ansible,Ansible Playbook,Idempotent,我正在使用ansible自动化堆栈部署。我使用“shell”或“command”模块来执行大部分任务。因此,为了使playbook具有shell和module的幂等元,我修改了playbook,如下所示 - name: Task1 shell: 'source /etc/nova/openrc && heat stack-show myne01 | tee stack_show.log' args: creates: stack_show.log regist

我正在使用ansible自动化堆栈部署。我使用“shell”或“command”模块来执行大部分任务。因此,为了使playbook具有shell和module的幂等元,我修改了playbook,如下所示

- name: Task1
  shell: 'source /etc/nova/openrc && heat stack-show myne01 | tee stack_show.log'
  args:
    creates: stack_show.log
  register: list
- debug: var=list.stdout_lines
  ignore_errors: yes

- name: Delete stack-show.log
  file: path=/home/wrsroot/stack_show.log state=absent
  when: "list.rc != 0"

- name: Failed the stack
  shell: "echo 'stack is failed'"
  when: "list.rc != 0"
  failed_when: "list.rc != 0"
这里的流程是:

1) 显示堆栈状态
2) 如果堆栈执行失败,请忽略错误并删除“stack_show.log”文件,以便重新运行Anisable时不会跳过此任务。
3) 如果堆栈执行失败,则任务失败

如果有更好的方法,请提出建议


为了在playbook中添加幂等性,我为每个“shell”模块添加了9行代码。这让我的剧本变得非常大。

你只需要在:false时更改
就可以成为幂等的。
此外,我认为你可以更简单地做到这一点:

- name: Task1
  shell: bash -c 'set -o pipefail;source /etc/nova/openrc && heat stack-show myne01 | tee stack_show.log'
  changed_when: false
  args:
    creates: stack_show.log
  register: list

- name: Delete stack-show.log
  file: path=/home/wrsroot/stack_show.log state=absent
  changed_when: false
  # You don't need this because file will deleted if exists
  #  when: "list.rc != 0"

# You don't need it because command will failed 
# set -o pipefail
#- name: Failed the stack
#  shell: "echo 'stack is failed'"
#  when: "list.rc != 0"
#  failed_when: "list.rc != 0"
你试试看

tasks:
     - block:
         - shell: bash -c 'set -o pipefail;source /etc/nova/openrc && heat stack-show myne01 | tee stack_show.log'
           changed_when: false
           args:
              creates: stack_show.log
            register: list

       always:
         - debug: msg="this always executes"    
         - name: Delete stack-show.log
              file: path=/home/wrsroot/stack_show.log state=absent
              changed_when: false