![如何让 Ansible 在少数节点上逐个运行批量任务(在集群中运行的节点)](https://linux22.com/image/772200/%E5%A6%82%E4%BD%95%E8%AE%A9%20Ansible%20%E5%9C%A8%E5%B0%91%E6%95%B0%E8%8A%82%E7%82%B9%E4%B8%8A%E9%80%90%E4%B8%AA%E8%BF%90%E8%A1%8C%E6%89%B9%E9%87%8F%E4%BB%BB%E5%8A%A1%EF%BC%88%E5%9C%A8%E9%9B%86%E7%BE%A4%E4%B8%AD%E8%BF%90%E8%A1%8C%E7%9A%84%E8%8A%82%E7%82%B9%EF%BC%89.png)
我有一个 ansible 剧本,大致如下:
- hosts: node1
tasks:
- name: get cluster state
shell: "RESTAPI 1 command"
- name: put cluster in upgrade mode
shell: "RESTAPI 2 command"
- hosts: node 1
tasks:
- name: upgrade Apache
shell: "upgrade Apache command"
- name: start Apache
shell: "start Apache command"
- hosts: node 1
tasks:
- name: healthy check for Apache is running
shell: "RESTAPI command"
- hosts: node 2
tasks:
- name: upgrade Apache
shell: "upgrade Apache command"
- name: start Apache
shell: "start Apache command"
- hosts: node 2
tasks:
- name: healthy check for Apache is running
shell: "RESTAPI command"
- hosts: node 3
tasks:
- name: upgrade Apache
shell: "upgrade Apache command"
- name: start Apache
shell: "start Apache command"
- hosts: node 3
tasks:
- name: healthy check for Apache is running
shell: "RESTAPI command"
我想改进以循环运行的剧本,因为对于每个节点,我都有相同的命令,这些命令应该在每个节点上逐个执行,因为所有节点都在集群中运行,而我只需要一个节点同时处于升级过程中。另外我有几个环境(测试/开发)我想使用这个剧本,但是集群中的节点数不同,无论集群中有多少个节点,我怎样才能运行剧本?
答案1
您可以将全部重复任务放在一个块中。 结合使用以serial: 1
确保每次只执行一个块。
- hosts: nodes
serial: 1
tasks:
- name: get cluster state
shell: "RESTAPI 1 command"
run_once: yes
- name: put cluster in upgrade mode
shell: "RESTAPI 2 command"
run_once: yes
- block:
- name: upgrade Apache
shell: "upgrade Apache command"
- name: start Apache
shell: "start Apache command"
- name: healthy check for Apache is running
shell: "RESTAPI command"
# retries: 20
# delay: 15
我假设将集群置于升级模式的命令可以在任何节点上运行,因此您只需使用即可run_once
。如果不是这种情况,并且必须在特定节点上运行,您可以when
对特定主机使用限制。
对于健康检查,如果存在检查最初失败而在 apache 完全运行时成功的可能性,那么参数delay
可能会引起人们的兴趣。retries
要在不同的主机组上使用剧本,您可以使用hosts: all
,然后在执行期间将主机限制在一个组中。
ansible-playbook upgrade.yml --limit dev_nodes