【问题标题】:Optimize playbook to make it idempotent with shell module优化 playbook 使其与 shell 模块幂等
【发布时间】:2016-05-22 05:32:57
【问题描述】:

我正在使用 ansible 自动化堆栈部署。我正在使用“shell”或“c​​ommand”模块来执行大部分任务。因此,为了使剧本与外壳和模块具有幂等性,我正在像这样修改剧本..

- 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”文件,这样在重新运行 anisble 时不会跳过此任务。
3) 如果堆栈执行失败,则任务失败。

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

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

【问题讨论】:

    标签: ansible ansible-playbook idempotent


    【解决方案1】:

    你只需要changed_when: 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"
    

    你猫试试Ansible 2.x Blocks

    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
    

    【讨论】:

      猜你喜欢
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      相关资源
      最近更新 更多