---
- hosts: S2985
  gather_facts: false
  connection: network_cli
 
  vars:
    ansible_user: admin
    ansible_ssh_pass: admin
    ansible_network_os: ios

  tasks:
    - name: Get model and version
      ios_command:
        commands: show version
      register: sh_ver
        
    - name: Parse output
      set_fact:
           switch_facts: "{{sh_ver.stdout[0] | parse_cli_textfsm('sh_ver.textFSM') }}"
    
    - name: Checking Model
      when:
        switch_facts[0]['Model'] != model
      fail:
        msg: Model is not {{model}}
     
    - name: Checking Version
      when:
        switch_facts[0]['SoftwareVersion'] == lastFW
      fail:
        msg: Version is actual {{lastFW}}

    - name: Upgrading FW
      ios_command:
         commands:
           - command: 'copy {{upgradeurl}}/{{FWfilename}} nos.img'
             prompt: '\[Y/N\]:'
             answer: 'y'
      vars:
        ansible_command_timeout: 300
      register: cmd_res
   
    - name: Checking upgrade result
      when:
        cmd_res.stdout[0].find('Write ok.') == -1 or
        cmd_res.stdout[0].find('Recv total {{FWSize}} bytes') == -1
      fail:
         msg: Upgrade fail {{ cmd_res.stdout}}

    - name: Switch save
      ios_command:
        commands:
          - command: 'write'
            prompt: '\[Y/N\]:'
            answer: 'y'
             
    - name: Switch reboot
      ios_command:
        commands:
         - command: 'reload'
           prompt: '\[Y/N\]'
           answer: 'y'
      ignore_errors: yes
  
    - name: WAIT FOR SWITCH TO RETURN
      wait_for:
         host: "{{inventory_hostname}}"
         port: 22
         delay: 60
         timeout: 600
      delegate_to: localhost
     
    - name: Get model and version
      ios_command:
        commands: show version
      register: sh_ver
        
    - name: Parse output
      set_fact:
        switch_facts: "{{sh_ver.stdout[0] | parse_cli_textfsm('sh_ver.textFSM') }}"
      
    - name: Checking Version
      debug:
        msg: "{{switch_facts[0]['SoftwareVersion']}}"
