Search code examples
ansiblechocolatey

Check if Chocolatey is installed in Ansible


I've recently started using Ansible and trying to apply it in an environment that doesn't have access to the Internet.

I've managed to create a playbook that installs Chocolatey using files and templates but at the moment it installs Chocolatey every time I run the playbook. The tasks that I'm currently using are:

---
- name: Create C:\temp
  win_file:
    path: C:\temp
    state: directory

- name: Save InstallChocolatey.ps1 file
  template:
    src: InstallChocolatey.ps1.j2
    dest: c:\temp\InstallChocolatey.ps1

- name: Run InstallChocolatey.ps1
  win_shell: C:\temp\InstallChocolatey.ps1

Is there a way to check if Chocolatey is already installed? Using this, I will be able to use a block and when to avoid performing the actions repeatedly.

Thanks for any recommendations people may have :)


Solution

  • You can add a task to check choco command is ready. And execute script InstallChocolatey.ps1 when choco is not available.

    ---
    - name: Check if Chocolatey is already installed
      win_shell: (Get-Command choco).Path
      register: get_command_choco
    
    - name: Create C:\temp
      win_file:
        path: C:\temp
        state: directory
    
    - name: Save InstallChocolatey.ps1 file
      template:
        src: InstallChocolatey.ps1.j2
        dest: c:\temp\InstallChocolatey.ps1
    
    - name: Run InstallChocolatey.ps1
      win_shell: C:\temp\InstallChocolatey.ps1
      when: not get_command_choco.stderr == ""