使用Ansible无法停止现有GCP实例的问题求助
问题描述
尝试用Ansible停止一台GCP现有实例,编写的Playbook如下:
- name: Stop an instance hosts: virtualmachines gather_facts: false tasks: - name: Stop an instance google.cloud.gcp_compute_instance: project: <project name> machine_type: <type> name: <name> zone: <zone> service_account_file: <file_path> auth_kind: "serviceaccount" status: stopped state: present deletion_protection: true
执行后Playbook返回changed状态,但实例并未停止,执行结果如下:
PLAY [Stop an instance] ***************************************************************************************************************************************************************** TASK [Stop an instance] ***************************************************************************************************************************************************************** changed: [vm01] PLAY RECAP ****************************************************************************************************************************************************************************** vm01 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
问题原因
google.cloud.gcp_compute_instance模块的核心作用是管理实例的存在状态(创建/删除实例),而非控制实例的运行状态(启动/停止)。即便指定了status: stopped,当state: present时,该模块只会确保实例存在,不会主动修改实例的运行状态,因此无法触发停止操作。
解决方案
改用专门用于停止GCP实例的google.cloud.gcp_compute_instance_stop模块,修改后的Playbook如下:
- name: Stop an instance hosts: virtualmachines gather_facts: false tasks: - name: Stop the GCP instance google.cloud.gcp_compute_instance_stop: project: <project name> name: <name> zone: <zone> service_account_file: <file_path> auth_kind: "serviceaccount" register: stop_result - name: Print stop result debug: var: stop_result
补充说明
- 该模块仅负责停止运行中的实例,无需指定
machine_type、deletion_protection这类实例属性参数 - 若实例已处于停止状态,模块会返回
ok而非changed,不会执行任何额外操作
内容的提问来源于stack exchange,提问作者Shreyas Ramachandran
相关产品推荐
相关产品推荐

