我有一个 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