--- - name: Apply Netplan configuration with automatic rollback on error block: - name: Deploy disable cloud-init message ansible.builtin.copy: dest: /etc/cloud/cloud-init.disabled src: cloud-init.disabled owner: root group: root mode: '0644' - name: Disable old netplan configuration files ansible.builtin.command: cmd: "mv {{ item }} {{ item }}.disabled" removes: "{{ item }}" # ファイルがない場合にエラーを発生させない loop: - /etc/netplan/00-installer-config.yaml - /etc/netplan/50-cloud-init.yaml - name: Fetch netplan configuration files ansible.builtin.fetch: src: /etc/netplan/10-ansible-netplan.yaml dest: "{{ fetch_dir }}/{{ inventory_hostname }}_10-ansible-netplan.yaml" flat: true ignore_errors: true - name: Deploy netplan configuration files ansible.builtin.copy: src: "{{ inventory_hostname }}/10-ansible-netplan.yaml" dest: /etc/netplan/10-ansible-netplan.yaml owner: root group: root mode: '0600' register: deploy_result - name: Validate netplan configuration syntax ansible.builtin.command: netplan generate when: deploy_result.changed changed_when: false - name: Confirm and permanently apply Netplan configuration ansible.builtin.command: netplan apply # tryしても即座に確定するためテストは不可能 async: 3 # 通信ができなくなると処理が停止するため非同期で実行 poll: 0 when: deploy_result.changed - name: Verify SSH connectivity after configuration change ansible.builtin.wait_for: host: "{{ ansible_host }}" port: "{{ ansible_port | default(22) }}" state: started delay: 2 timeout: 5 delegate_to: localhost register: do_verify when: deploy_result.changed # 何らかの異常が発生した場合への対応 rescue: - name: "[RESCUE] Re-enable disabled old Netplan files" ansible.builtin.copy: dest: /etc/netplan/10-ansible-netplan.yaml src: "{{ fetch_dir }}/{{ inventory_hostname }}_10-ansible-netplan.yaml" mode: '0600' when: - do_verify is undefined - deploy_result is defined - deploy_result.changed - name: "[RESCUE] Fail playbook execution with error notification" ansible.builtin.fail: msg: >- {{ 'SSH connection lost after netplan apply. Remote rollback is unavailable.' if do_verify is defined else 'Netplan configuration failed before apply and was safely rolled back.' }}