Ansible установка программ в windows

Note

This module is part of the ansible.windows collection (version 1.14.0).

You might already have this collection installed if you are using the ansible package.
It is not included in ansible-core.
To check whether it is installed, run ansible-galaxy collection list.

To install it, use: ansible-galaxy collection install ansible.windows.

To use it in a playbook, specify: ansible.windows.win_package.

Synopsis

  • Installs or uninstalls software packages for Windows.

  • Supports .exe, .msi, .msp, .appx, .appxbundle, .msix, and .msixbundle.

  • These packages can be sourced from the local file system, network file share or a url.

  • See provider for more info on each package type that is supported.

Parameters

Parameter

Comments

arguments

any

Any arguments the installer needs to either install or uninstall the package.

If the package is an MSI do not supply the /qn, /log or /norestart arguments.

This is only used for the msi, msp, and registry providers.

Can be a list of arguments and the module will escape the arguments as necessary, it is recommended to use a string when dealing with MSI packages due to the unique escaping issues with msiexec.

When using a list of arguments each item in the list is considered to be a single argument. As such, if an argument in the list contains a space then Ansible will quote this to ensure that this is seen by Windows as a single argument. Should this behaviour not be what is required, the argument should be split into two separate list items. See the examples section for more detail.

chdir

path

Set the specified path as the current working directory before installing or uninstalling a package.

This is only used for the msi, msp, and registry providers.

client_cert

string

The path to the client certificate (.pfx) that is used for X509 authentication. This path can either be the path to the pfx on the filesystem or the PowerShell certificate path Cert:\CurrentUser\My\<thumbprint>.

The WinRM connection must be authenticated with CredSSP or become is used on the task if the certificate file is not password protected.

Other authentication types can set client_cert_password when the cert is password protected.

client_cert_password

string

The password for client_cert if the cert is password protected.

creates_path

path

Will check the existence of the path specified and use the result to determine whether the package is already installed.

You can use this in conjunction with product_id and other creates_*.

creates_service

string

Will check the existing of the service specified and use the result to determine whether the package is already installed.

You can use this in conjunction with product_id and other creates_*.

creates_version

string

Will check the file version property of the file at creates_path and use the result to determine whether the package is already installed.

creates_path MUST be set and is a file.

You can use this in conjunction with product_id and other creates_*.

expected_return_code

list / elements=integer

One or more return codes from the package installation that indicates success.

The return codes are read as a signed integer, any values greater than 2147483647 need to be represented as the signed equivalent, i.e. 4294967295 is -1.

To convert a unsigned number to the signed equivalent you can run “[Int32](“0x{0:X}” -f ([UInt32]3221225477))”.

A return code of 3010 usually means that a reboot is required, the reboot_required return value is set if the return code is 3010.

This is only used for the msi, msp, and registry providers.

Default: [0, 3010]

follow_redirects

string

Whether or the module should follow redirects.

all will follow all redirect.

none will not follow any redirect.

safe will follow only “safe” redirects, where “safe” means that the client is only doing a GET or HEAD on the URI to which it is being redirected.

When following a redirected URL, the Authorization header and any credentials set will be dropped and not redirected.

Choices:

  • "all"

  • "none"

  • "safe" ← (default)

force_basic_auth

boolean

By default the authentication header is only sent when a webservice responses to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins will fail.

This option forces the sending of the Basic authentication header upon the original request.

Choices:

  • false ← (default)

  • true

dictionary

Extra headers to set on the request.

This should be a dictionary where the key is the header name and the value is the value for that header.

http_agent

string

Header to identify as, generally appears in web server logs.

This is set to the User-Agent header on a HTTP request.

Default: "ansible-httpget"

log_path

path

Specifies the path to a log file that is persisted after a package is installed or uninstalled.

This is only used for the msi or msp provider.

When omitted, a temporary log file is used instead for those providers.

This is only valid for MSI files, use arguments for the registry provider.

maximum_redirection

integer

Specify how many times the module will redirect a connection to an alternative URI before the connection fails.

If set to 0 or follow_redirects is set to none, or safe when not doing a GET or HEAD it prevents all redirection.

Default: 50

password

aliases: user_password

string

The password for user_name, must be set when user_name is.

This option is deprecated in favour of using become, see examples for more information. Will be removed on the major release after 2022-07-01.

path

string

Location of the package to be installed or uninstalled.

This package can either be on the local file system, network share or a url.

When state=present, product_id is not set and the path is a URL, this file will always be downloaded to a temporary directory for idempotency checks, otherwise the file will only be downloaded if the package has not been installed based on the product_id checks.

If state=present then this value MUST be set.

If state=absent then this value does not need to be set if product_id is.

product_id

aliases: productid

string

The product id of the installed packaged.

This is used for checking whether the product is already installed and getting the uninstall information if state=absent.

For msi packages, this is the ProductCode (GUID) of the package. This can be found under the same registry paths as the registry provider.

For msp packages, this is the PatchCode (GUID) of the package which can found under the Details -> Revision number of the file’s properties.

For msix packages, this is the Name or PackageFullName of the package found under the Get-AppxPackage cmdlet.

For registry (exe) packages, this is the registry key name under the registry paths specified in provider.

This value is ignored if path is set to a local accesible file path and the package is not an exe.

This SHOULD be set when the package is an exe, or the path is a url or a network share and credential delegation is not being used. The creates_* options can be used instead but is not recommended.

The alias productid is deprecated and will be removed on the major release after 2022-07-01.

provider

string

Set the package provider to use when searching for a package.

The auto provider will select the proper provider if path otherwise it scans all the other providers based on the product_id.

The msi provider scans for MSI packages installed on a machine wide and current user context based on the ProductCode of the MSI.

The msix provider is used to install .appx, .msix, .appxbundle, or .msixbundle packages. These packages are only installed or removed on the current use. The host must be set to allow sideloaded apps or in developer mode. See the examples for how to enable this. If a package is already installed but path points to an updated package, this will be installed over the top of the existing one.

The msp provider scans for all MSP patches installed on a machine wide and current user context based on the PatchCode of the MSP. A msp will be applied or removed on all msi products that it applies to and is installed. If the patch is obsoleted or superseded then no action will be taken.

The registry provider is used for traditional exe installers and uses the following registry path to determine if a product was installed; HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall, HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall, and HKCU:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall.

Choices:

  • "auto" ← (default)

  • "msi"

  • "msix"

  • "msp"

  • "registry"

proxy_password

string

The password for proxy_username.

proxy_url

string

An explicit proxy to use for the request.

By default, the request will use the IE defined proxy unless use_proxy is set to no.

proxy_use_default_credential

boolean

Uses the current user’s credentials when authenticating with a proxy host protected with NTLM, Kerberos, or Negotiate authentication.

Proxies that use Basic auth will still require explicit credentials through the proxy_username and proxy_password options.

The module will only have access to the user’s credentials if using become with a password, you are connecting with SSH using a password, or connecting with WinRM using CredSSP or Kerberos with delegation.

If not using become or a different auth method to the ones stated above, there will be no default credentials available and no proxy authentication will occur.

Choices:

  • false ← (default)

  • true

proxy_username

string

The username to use for proxy authentication.

state

aliases: ensure

string

Whether to install or uninstall the package.

The module uses product_id to determine whether the package is installed or not.

For all providers but auto, the path can be used for idempotency checks if it is locally accesible filesystem path.

The alias ensure is deprecated and will be removed on the major release after 2022-07-01.

Choices:

  • "absent"

  • "present" ← (default)

url_method

string

The HTTP Method of the request.

url_password

string

The password for url_username.

url_timeout

integer

Specifies how long the request can be pending before it times out (in seconds).

Set to 0 to specify an infinite timeout.

Default: 30

url_username

string

The username to use for authentication.

use_default_credential

boolean

Uses the current user’s credentials when authenticating with a server protected with NTLM, Kerberos, or Negotiate authentication.

Sites that use Basic auth will still require explicit credentials through the url_username and url_password options.

The module will only have access to the user’s credentials if using become with a password, you are connecting with SSH using a password, or connecting with WinRM using CredSSP or Kerberos with delegation.

If not using become or a different auth method to the ones stated above, there will be no default credentials available and no authentication will occur.

Choices:

  • false ← (default)

  • true

use_proxy

boolean

If no, it will not use the proxy defined in IE for the current user.

Choices:

  • false

  • true ← (default)

username

aliases: user_name

string

Username of an account with access to the package if it is located on a file share.

This is only needed if the WinRM transport is over an auth method that does not support credential delegation like Basic or NTLM or become is not used.

This option is deprecated in favour of using become, see examples for more information. Will be removed on the major release after 2022-07-01.

validate_certs

boolean

If no, SSL certificates will not be validated.

This should only be used on personally controlled sites using self-signed certificates.

Choices:

  • false

  • true ← (default)

wait_for_children

boolean

added in ansible.windows 1.3.0

The module will wait for the process it spawns to finish but any processes spawned in that child process as ignored.

Set to true to wait for all descendent processes to finish before the module returns.

This is useful if the install/uninstaller is just a wrapper which then calls the actual installer as its own child process. When this option is true then the module will wait for both processes to finish before returning.

This should not be required for most installers and setting to true could result in the module not returning until the process it is waiting for has been stopped manually.

Requires Windows Server 2012 or Windows 8 or newer to use.

Choices:

  • false ← (default)

  • true

Notes

Note

  • When state=absent and the product is an exe, the path may be different from what was used to install the package originally. If path is not set then the path used will be what is set under QuietUninstallString or UninstallString in the registry for that product_id.

  • By default all msi installs and uninstalls will be run with the arguments /log, /qn, /norestart.

  • All the installation checks under product_id and creates_* add together, if one fails then the program is considered to be absent.

See Also

Examples

- name: Install the Visual C thingy
  ansible.windows.win_package:
    path: http://download.microsoft.com/download/1/6/B/16B06F60-3B20-4FF2-B699-5E9B7962F9AE/VSU_4/vcredist_x64.exe
    product_id: '{CF2BEA3C-26EA-32F8-AA9B-331F7E34BA97}'
    arguments: /install /passive /norestart

- name: Install Visual C thingy with list of arguments instead of a string
  ansible.windows.win_package:
    path: http://download.microsoft.com/download/1/6/B/16B06F60-3B20-4FF2-B699-5E9B7962F9AE/VSU_4/vcredist_x64.exe
    product_id: '{CF2BEA3C-26EA-32F8-AA9B-331F7E34BA97}'
    arguments:
    - /install
    - /passive
    - /norestart

- name: Install MSBuild thingy with arguments split to prevent quotes
  ansible.windows.win_package:
    path: https://download.visualstudio.microsoft.com/download/pr/9665567e-f580-4acd-85f2-bc94a1db745f/vs_BuildTools.exe
    product_id: '{D1437F51-786A-4F57-A99C-F8E94FBA1BD8}'
    arguments:
    - --norestart
    - --passive
    - --wait
    - --add
    - Microsoft.Net.Component.4.6.1.TargetingPack
    - --add
    - Microsoft.Net.Component.4.6.TargetingPack

- name: Install Remote Desktop Connection Manager from msi with a permanent log
  ansible.windows.win_package:
    path: https://download.microsoft.com/download/A/F/0/AF0071F3-B198-4A35-AA90-C68D103BDCCF/rdcman.msi
    product_id: '{0240359E-6A4C-4884-9E94-B397A02D893C}'
    state: present
    log_path: D:\logs\vcredist_x64-exe-{{lookup('pipe', 'date +%Y%m%dT%H%M%S')}}.log

- name: Install Application from msi with multiple properties for installer
  ansible.windows.win_package:
    path: C:\temp\Application.msi
    state: present
    arguments: >-
      SERVICE=1
      DBNAME=ApplicationDB
      DBSERVER=.\SQLEXPRESS
      INSTALLDIR="C:\Program Files (x86)\App lication\App Server"

- name: Install Microsoft® SQL Server® 2019 Express (DPAPI example)
  ansible.windows.win_package:
    path: C:\temp\SQLEXPR_x64_ENU\SETUP.EXE
    product_id: Microsoft SQL Server SQL2019
    arguments:
      - SAPWD=VeryHardPassword
      - /ConfigurationFile=C:\temp\configuration.ini
  become: true
  vars:
    ansible_become_method: runas
    ansible_become_user: "{{ user }}"
    ansible_become_pass: "{{ password }}"

- name: Uninstall Remote Desktop Connection Manager
  ansible.windows.win_package:
    product_id: '{0240359E-6A4C-4884-9E94-B397A02D893C}'
    state: absent

- name: Install Remote Desktop Connection Manager locally omitting the product_id
  ansible.windows.win_package:
    path: C:\temp\rdcman.msi
    state: present

- name: Uninstall Remote Desktop Connection Manager from local MSI omitting the product_id
  ansible.windows.win_package:
    path: C:\temp\rdcman.msi
    state: absent

# 7-Zip exe doesn't use a guid for the Product ID
- name: Install 7zip from a network share with specific credentials
  ansible.windows.win_package:
    path: \\domain\programs\7z.exe
    product_id: 7-Zip
    arguments: /S
    state: present
  become: true
  become_method: runas
  become_flags: logon_type=new_credential logon_flags=netcredentials_only
  vars:
    ansible_become_user: DOMAIN\User
    ansible_become_password: Password

- name: Install 7zip and use a file version for the installation check
  ansible.windows.win_package:
    path: C:\temp\7z.exe
    creates_path: C:\Program Files\7-Zip\7z.exe
    creates_version: 16.04
    state: present

- name: Uninstall 7zip from the exe
  ansible.windows.win_package:
    path: C:\Program Files\7-Zip\Uninstall.exe
    product_id: 7-Zip
    arguments: /S
    state: absent

- name: Uninstall 7zip without specifying the path
  ansible.windows.win_package:
    product_id: 7-Zip
    arguments: /S
    state: absent

- name: Install application and override expected return codes
  ansible.windows.win_package:
    path: https://download.microsoft.com/download/1/6/7/167F0D79-9317-48AE-AEDB-17120579F8E2/NDP451-KB2858728-x86-x64-AllOS-ENU.exe
    product_id: '{7DEBE4EB-6B40-3766-BB35-5CBBC385DA37}'
    arguments: '/q /norestart'
    state: present
    expected_return_code: [0, 666, 3010]

- name: Install a .msp patch
  ansible.windows.win_package:
    path: C:\Patches\Product.msp
    state: present

- name: Remove a .msp patch
  ansible.windows.win_package:
    product_id: '{AC76BA86-A440-FFFF-A440-0C13154E5D00}'
    state: absent

- name: Enable installation of 3rd party MSIX packages
  ansible.windows.win_regedit:
    path: HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock
    name: AllowAllTrustedApps
    data: 1
    type: dword
    state: present

- name: Install an MSIX package for the current user
  ansible.windows.win_package:
    path: C:\Installers\Calculator.msix  # Can be .appx, .msixbundle, or .appxbundle
    state: present

- name: Uninstall an MSIX package using the product_id
  ansible.windows.win_package:
    product_id: InputApp
    state: absent

Return Values

Common return values are documented here, the following are the fields unique to this module:

Key

Description

log

string

The contents of the MSI or MSP log.

Returned: installation/uninstallation failure for MSI or MSP packages

Sample: "Installation completed successfully"

rc

integer

The return code of the package process.

Returned: change occurred

Sample: 0

reboot_required

boolean

Whether a reboot is required to finalise package. This is set to true if the executable return code is 3010.

Returned: always

Sample: true

stderr

string

The stderr stream of the package process.

Returned: failure during install or uninstall

Sample: "Failed to install program"

stdout

string

The stdout stream of the package process.

Returned: failure during install or uninstall

Sample: "Installing program"

Collection links

  • Issue Tracker
  • Repository (Sources)
  • Communication

By this time most of the readers on this blog know I am an automation junkie and Ansible is my dealer. I started using Chocolatey about 2 years ago as it is an efficient open-source package manager for Windows operating systems similar to what brew is for Mac OS systems. In today’s tutorial, I am going to cover how to use Chocolatey and Ansible together to manage desktop apps on Windows operating systems.

Prerequisite Initial Steps

The initial steps would be to have Ansible set up already and Chocolatey installed on your Windows machine. You can follow the tutorials below to set up Ansible and install Chocolatey:

How To Set Up Ansible Inside A Github Repository And Automate Your Workloads

Ansible is an open-source configuration management and IT automation platform. Let’s jump in and set up our Ansible Github repository and run an example automation playbook.

Opensource GeeksChad Crouch

Installing Chocolatey

Chocolatey is software management automation for Windows that wraps installers, executables, zips, and scripts into compiled packages. Chocolatey integrates w/SCCM, Puppet, Chef, etc. Chocolatey is trusted by businesses to manage software deployments.

Chocolatey Software

Script To Set Ansible Connection To Windows Host Locally Via WSL

WSL also known as Windows Subsystem For Linux is a lightweight virtual machine that you can enable to run Linux on your Windows computer. Ensure that you set up WSL by following these steps:

Install Ubuntu on WSL2 on Windows 10 | Ubuntu

Ubuntu is an open source software operating system that runs from the desktop, to the cloud, to all your internet connected things.

Ubuntu

Once WSL is installed and Ansible and Chocolatey are set up. Copy the Powershell script below and name it windows-host-setup.ps1. Navigate to the directory and run this command to execute the setup that will allow you to access your Windows localhost through WSL — powershell.exe -ExecutionPolicy ByPass -File "windows-host-setup.ps1"

$url = "https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1"
$file = "$env:temp\ConfigureRemotingForAnsible.ps1"
(New-Object -TypeName System.Net.WebClient).DownloadFile($url, $file)
powershell.exe -ExecutionPolicy ByPass -File $file

Set Up Inventory And Playbooks

Once the above script is executed successfully the next steps are to add your inventory file and playbook to manage your desktop apps on your Windows system. Create a directory called  choco and add localhost_inventory.yml and desktop_apps.yml and copy the scripts below:

#localhost_inventory.yml

all:
  hosts: localhost
  vars:
    ansible_user: user #add your windows username here
    ansible_connection: winrm
    ansible_winrm_server_cert_validation: ignore
#desktop_apps.yml
---
- hosts: localhost
  connection: local
  tasks:
    - name: Install/Uninstall/Update Chromium
      win_chocolatey:
        name:
        - chromium
        state: absent

    - name: Install/Uninstall/Update Slack
      win_chocolatey:
        name:
        - slack
        state: present

    - name: Install/Uninstall/Update Telegram
      win_chocolatey:
        name:
        - telegram
        state: latest

The desktop_apps.yml script can be updated by looking at the chocolatey package website to see which packages are available to install. In this tutorial we are going to uninstall Chromium, ensure that Slack is installed else it will be installed, update Telegram to the latest version if installed, and if not install the latest version. This ansible module states work as follows:

  • absent — uninstall package/software
  • present — ensure the software is installed and if not install the latest version
  • latest — update software to the latest version and if it does not exist install the latest version

Once all the above steps are completed run the following command to execute this Ansible playbook — ansible-playbook choco/desktop_apps.yml -i choco/localhost_inventory.yml --ask-pass --verbose and you will be prompted to input your Windows password.

Ansible Playbook Chocolatey

Once successful you can search for the apps and should see that you have installed or updated your desktop apps to the latest version like in this example below.

Telegram Installed

Conclusion

In conclusion, Chocolatey is an awesome open-source package manager for Windows operating systems and has a large community behind it. If you enjoyed this article consider signing up for our newsletter and don’t forget to share it with people that would find it useful. Leave a comment below with a tutorial you would like us to cover.

Note

Этот плагин является частью ansible.windows collection (версия 1.7.3).).

Возможно, у вас уже установлена эта коллекция, если вы используете пакет ansible . Он не включен в ansible-core . Чтобы проверить, установлен ли он, запустите ansible-galaxy collection list .

Для его установки используйте: ansible-galaxy collection install ansible.windows .

Чтобы использовать его в плейбуке, укажите: ansible.windows.win_package .

Parameter Choices/Defaults Comments
arguments

raw

Любые аргументы, необходимые установщику для установки или удаления пакета.

Если пакет представляет собой MSI, не указывайте аргументы /qn , /log или /norestart .

Это используется только для провайдеров msi , msp и registry .

Может быть списком аргументов, и модуль будет экранировать аргументы по мере необходимости. Рекомендуется использовать строку при работе с пакетами MSI из-за уникальных проблем экранирования с msiexec.

При использовании списка аргументов каждый элемент списка считается одним аргументом. Таким образом, если аргумент в списке содержит пробел, Ansible заключает его в кавычки, чтобы убедиться, что Windows воспринимает его как один аргумент. Если такое поведение не соответствует требованиям, аргумент следует разделить на два отдельных элемента списка. См. раздел примеров для более подробной информации.

chdir

path

Установите указанный путь в качестве текущего рабочего каталога перед установкой или удалением пакета.

Это используется только для провайдеров msi , msp и registry .

client_cert

string

Путь к сертификату клиента (.pfx), который используется для проверки подлинности X509. Этот путь может быть либо путем к pfx в файловой системе, либо путем сертификата PowerShell Cert:\CurrentUser\My\<thumbprint> .

Соединение WinRM должно быть аутентифицировано с помощью CredSSP , или become используется в задаче, если файл сертификата не имеет пароля protected.

Другие типы аутентификации могут устанавливать client_cert_password, если сертификат имеет пароль protected.

client_cert_password

string

Пароль для client_cert, если сертификат protected.

creates_path

path

Проверит существование указанного пути и использует результат, чтобы определить, установлен ли уже пакет.

Вы можете использовать это в сочетании с product_id и другими creates_* .

creates_service

string

Проверит наличие указанной службы и использует результат, чтобы определить, установлен ли уже пакет.

Вы можете использовать это в сочетании с product_id и другими creates_* .

creates_version

string

Проверит свойство версии файла на creates_path и использует результат, чтобы определить, установлен ли уже пакет.

creates_path MUST устанавливается и представляет собой файл.

Вы можете использовать это в сочетании с product_id и другими creates_* .

expected_return_code

список / elements=integer

Default:

[0, 3010]

Один или несколько кодов возврата из установки пакета, указывающих на успех.

Коды возврата читаются как целое число со знаком, любые значения больше 2147483647 должны быть представлены как эквивалент со знаком, i.e. 4294967295 — это -1 .

Чтобы преобразовать беззнаковое число в эквивалентное со знаком, вы можете запустить «[Int32](«0x{0:X}» -f ([UInt32]3221225477))»..

Код возврата 3010 обычно означает, что требуется перезагрузка, значение возврата reboot_required устанавливается, если код возврата 3010 .

Это используется только для провайдеров msi , msp и registry .

follow_redirects

string

    Choices:

  • all
  • none
  • safe

Должен ли модуль следовать перенаправлениям.

all будет следовать всем редиректам.

none не будет следовать никакому перенаправлению.

safe будет следовать только «безопасным» перенаправлениям, где «безопасный» означает, что клиент выполняет только GET или HEAD на URI, на который он перенаправляется.

При следовании перенаправленному URL, заголовок Authorization и любой набор учетных данных будут удалены и не перенаправлены.

force_basic_auth

boolean

    Choices:

  • no

  • yes

По умолчанию заголовок аутентификации отправляется только тогда, когда веб-служба отвечает на первоначальный запрос со статусом 401. Поскольку некоторые базовые службы аутентификации неправильно отправляют ошибку 401, вход в систему невозможен.

Этот параметр принудительно отправляет заголовок базовой аутентификации при исходном запросе.

headers

dictionary

Дополнительные заголовки для установки в запросе.

Это должен быть словарь, где ключ — это имя заголовка, а значение — значение для этого заголовка.

http_agent

string

Default:

«ansible-httpget»

Заголовок для идентификации обычно отображается в журналах веб-сервера.

Это устанавливается в заголовок User-Agent в запросе HTTP.

log_path

path

Указывает путь к файлу журнала, который сохраняется после установки или удаления пакета.

Это используется только для провайдера msi или msp .

Если этот параметр опущен, для этих поставщиков используется временный файл журнала.

Это действительно только для файлов MSI, используйте arguments для провайдера registry .

maximum_redirection

integer

Default:

50

Укажите, сколько раз модуль будет перенаправлять соединение на альтернативный URI, прежде чем произойдет сбой соединения.

Если установлено значение 0 или follow_redirects установлено значение none или safe , когда не выполняется GET или HEAD , это предотвращает все перенаправления.

password

string

Пароль для user_name должен быть установлен, когда user_name установлен.

Этот параметр устарел, вместо него используется становление, дополнительные сведения см. в примерах. Будет удален в основном выпуске после 2022-07-01 .

aliases: user_password

path

string

Местоположение пакета, который необходимо установить или удалить.

Этот пакет может находиться либо в локальной файловой системе, либо в сетевой папке, либо по URL-адресу.

Когда state=present , product_id не установлен, а путь URL,, этот файл всегда будет загружаться во временный каталог для проверки идемпотентности, в противном случае файл будет загружен только в том случае, если пакет не был установлен на основе проверок product_id .

Если state=present , тогда будет установлено это значение MUST.

Если state=absent , то это значение не нужно устанавливать, если product_id .

product_id

string

Идентификатор продукта установленного пакета.

Это используется для проверки того, установлен ли продукт уже и получения информации об удалении, если state=absent .

Для пакетов msi это ProductCode (GUID) пакета. Его можно найти по тем же путям реестра, что и поставщика registry .

Для пакетов MSP это PatchCode (GUID) пакета, который можно найти в Details -> Revision number свойств файла.

Для пакетов msix это Name или PackageFullName пакета, найденного в командлете Get-AppxPackage .

Для пакетов реестра (exe) это имя раздела реестра по путям реестра, указанным в provider.

Это значение игнорируется, если для path задан локальный доступный путь к файлу, а пакет не является exe .

Этот SHOULD должен быть установлен, если пакет представляет собой exe или путь представляет собой URL-адрес или общий сетевой ресурс, а делегирование учетных данных не используется. Вместо этого можно использовать опции creates_* , но это не рекомендуется.

Псевдоним productid устарел и будет удален в основном выпуске после 2022-07-01 .

aliases: productid

provider

string

    Choices:

  • auto

  • msi
  • msix
  • msp
  • registry

Установите поставщика пакетов для использования при поиске пакета.

Провайдер auto выберет правильного провайдера, если путь, в противном случае он сканирует всех других провайдеров на основе product_id..

Поставщик msi сканирует пакеты MSI, установленные на всей машине, и текущий пользовательский контекст на основе ProductCode MSI.

Поставщик msix используется для установки пакетов .appx , .msix , .appxbundle или .msixbundle . Эти пакеты устанавливаются или удаляются только при текущем использовании. Хост должен быть настроен на разрешение загрузки неопубликованных приложений или в режиме разработчика. См. примеры того, как включить это. Если пакет уже установлен, но path указывает на обновленный пакет, он будет установлен поверх существующего.

Поставщик msp сканирует все исправления MSP, установленные на всей машине, и текущий пользовательский контекст на основе PatchCode MSP. msp будет применен или удален для всех продуктов msi , к которым он применяется и установлен. Если патч устарел или заменен, никаких действий предприниматься не будет.

Поставщик registry используется для традиционных установщиков exe и использует следующий путь реестра, чтобы определить, был ли установлен продукт; HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall , HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall , HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall и HKCU:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall .

proxy_password

string

Пароль для proxy_username.

proxy_url

string

Явный прокси для использования для запроса.

По умолчанию запрос будет использовать прокси-сервер, определенный IE, если для use_proxy не установлено значение no .

proxy_use_default_credential

boolean

    Choices:

  • no

  • yes

Использует учетные данные текущего пользователя при аутентификации на прокси-узле protected с аутентификацией NTLM , Kerberos или Negotiate .

Прокси-серверы, использующие аутентификацию Basic , по-прежнему будут требовать явных учетных данных с помощью параметров proxy_username и proxy_password.

Модуль будет иметь доступ к учетным данным пользователя только в том случае, если вы используете become с паролем, вы подключаетесь к SSH с помощью пароля или подключаетесь к WinRM с помощью CredSSP или Kerberos with delegation .

Если не использовать become или метод аутентификации, отличный от указанных выше, учетные данные по умолчанию будут недоступны, и аутентификация прокси-сервера не произойдет.

proxy_username

string

Имя пользователя, используемое для аутентификации прокси.

state

string

    Choices:

  • absent
  • present

Установить или удалить пакет.

Модуль использует product_id, чтобы определить, установлен пакет или нет.

Для всех провайдеров, кроме auto , путь можно использовать для проверки идемпотентности, если он является локально доступным путем файловой системы.

Проверка псевдонима устарела и будет удалена в основном выпуске после 2022-07-01 .

aliases: ensure

url_method

string

Метод запроса HTTP.

url_password

string

Пароль для url_username.

url_timeout

integer

Default:

30

Указывает, как долго запрос может находиться в ожидании до истечения времени ожидания (в seconds).

Установите 0 , чтобы указать бесконечный тайм-аут.

url_username

string

Имя пользователя для аутентификации.

use_default_credential

boolean

    Choices:

  • no

  • yes

Использует учетные данные текущего пользователя при аутентификации на сервере protected с аутентификацией NTLM , Kerberos или Negotiate .

Сайты, использующие аутентификацию Basic , по-прежнему будут требовать явных учетных данных с помощью параметров url_username и url_password.

Модуль будет иметь доступ к учетным данным пользователя только в том случае, если вы используете become с паролем, вы подключаетесь к SSH с помощью пароля или подключаетесь к WinRM с помощью CredSSP или Kerberos with delegation .

Если не использовать become или метод аутентификации, отличный от указанных выше, учетные данные по умолчанию будут недоступны, и аутентификация не произойдет.

use_proxy

boolean

    Choices:

  • no
  • yes

Если no , он не будет использовать прокси-сервер, определенный в IE для текущего пользователя.

username

string

Имя пользователя учетной записи с доступом к пакету, если он находится в общей папке.

Это необходимо только в том случае, если транспорт WinRM использует метод аутентификации, который не поддерживает делегирование учетных данных, например Basic или NTLM, или не используется.

Этот параметр устарел, вместо него используется становление, дополнительные сведения см. в примерах. Будет удален в основном выпуске после 2022-07-01 .

aliases: user_name

validate_certs

boolean

    Choices:

  • no
  • yes

Если no , сертификаты SSL не будут проверены.

Это следует использовать только на лично контролируемых сайтах с использованием самозаверяющих сертификатов.

wait_for_children

boolean

добавлено в 1.3.0 ansible.windows

    Choices:

  • no

  • yes

Модуль будет ждать завершения порожденного им процесса, но любые процессы, порожденные в этом дочернем процессе, будут проигнорированы.

Установите значение yes , чтобы дождаться завершения всех дочерних процессов, прежде чем модуль вернется.

Это полезно, если install/uninstaller является просто оболочкой, которая затем вызывает фактический установщик как собственный дочерний процесс. Если этот параметр равен yes , модуль будет ждать завершения обоих процессов перед возвратом.

Это не требуется для большинства установщиков, и установка yes может привести к тому, что модуль не вернется, пока ожидаемый процесс не будет остановлен вручную.

Для использования требуется Windows Server 2012 или Windows 8 или новее.

Общие возвращаемые значения задокументированы here , следующие поля являются уникальными для этого модуля:

Key Returned Description
log

string

Ошибка installation/uninstallation для пакетов MSI или MSP

Содержимое журнала MSI или MSP.

Sample:

Установка завершена успешно

rc

integer

change occurred

Код возврата процесса пакета.

reboot_required

boolean

always

Требуется ли перезагрузка для финализации package. Устанавливается в true, если исполняемый код возврата равен 3010.

Sample:

True

stderr

string

сбой при установке или удалении

Поток stderr процесса пакета.

Sample:

Не удалось установить программу

stdout

string

сбой при установке или удалении

Поток stdout процесса пакета.

Sample:

Installing program

To Install an Application on Windows by using Ansible playbook

Introduction:

Ansible is an open-source tool for managing software configurations and deploying applications. Chocolately is a management tool for Windows software.

Master Server Requirements:

ansible

python3-pip

pywinrm (python package

Windows Requirements:

powershell 3+

Dot net 4

Installation Procedure:

Step 1: Search for chocolatey in browser
Snap 1

Step 2: Copy the installation command in chocolatey install page
Snap 2
Step 3: Run Powershell ISE as an administrator
Snap 3

Step 4: Install chocolatey by using the following command

PS C:\WINDOWS\system32> Set-ExecutionPolicy Bypass -Scope Process -Force; 

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
Forcing web requests to allow TLS v1.2 (Required for requests to Chocolatey.org)
Getting latest version of the Chocolatey package for download.
Not using proxy.
Getting Chocolatey from https://community.chocolatey.org/api/v2/package/chocolatey/0.11.3.
Downloading https://community.chocolatey.org/api/v2/package/chocolatey/0.11.3 to C:\Users\Admin\AppData\Local\Temp\chocolatey\chocoInstall\chocolatey.zip
Not using proxy.
Extracting C:\Users\Admin\AppData\Local\Temp\chocolatey\chocoInstall\chocolatey.zip to C:\Users\Admin\AppData\Local\Temp\chocolatey\chocoInstall
Installing Chocolatey on the local machine
Creating ChocolateyInstall as an environment variable (targeting 'Machine') 
  Setting ChocolateyInstall to 'C:\ProgramData\chocolatey'
WARNING: It's very likely you will need to close and reopen your shell 
  before you can use choco.
Restricting write permissions to Administrators
We are setting up the Chocolatey package repository.
The packages themselves go to 'C:\ProgramData\chocolatey\lib'
  (i.e. C:\ProgramData\chocolatey\lib\yourPackageName).
A shim file for the command line goes to 'C:\ProgramData\chocolatey\bin'
  and points to an executable in 'C:\ProgramData\chocolatey\lib\yourPackageName'.

Step 5: Check the OS version by using the following command

root@linuxhelp:~# lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 21.04
Release:	21.04
Codename:	hirsute

Step 6: Check the availability of Ansible package

root@linuxhelp:~# apt list -a ansible
Listing... Done
ansible/hirsute,hirsute,now 4.8.0-1ppa~hirsute all [installed]
ansible/hirsute,hirsute 2.10.7-1 all

Step 7: Check the availability of python3-pip package

root@linuxhelp:~# apt list -a python3
Listing... Done
python3/hirsute,now 3.9.4-1 amd64 [installed,automatic]

python3/hirsute 3.9.4-1 i386

Step 8: Check the availability of python package pywinrm

root@linuxhelp:~# pip list | grep pywinrm
pywinrm                0.4.2


ansible_winrm_server_cert_validation=ignore

Step 9: Install the plugins of chocolatey for ansible

root@linuxhelp:~# ansible-galaxy collection install chocolatey.chocolatey

Starting galaxy collection install process
Nothing to do. All requested collections are already installed. If you want to reinstall them, consider using `--force`.

Step 10:Create inventory for Windows node system

root@linuxhelp:~# vi /etc/ansible/hosts 

[windows]
192.168.2.134

[windows:vars]
ansible_user=Admin
ansible_password=Admin@123
ansible_port=5986
ansible_connection=winrm

Step 11:Create playbook for installing namecoin application

root@linuxhelp:~# vi install.yml
hosts: windows
  gather_facts: true
  tasks:
  - name: install namecoin
    win_chocolatey:
      name: namecoin
      state: present

Step 12: Check the syntax of the install.yml ansible playbook by using the following command

root@linuxhelp:~# ansible-playbook install.yml --syntax-check

playbook: proxyset.yml

Step 13: Run the install.yml playbook by using the following command

root@linuxhelp:~# ansible-playbook install.yml 

PLAY [windows] **************************************************************************************

TASK [Gathering Facts] ******************************************************************************
ok: [192.168.2.134]

TASK [install namecoin] *****************************************************************************
changed: [192.168.2.134]

PLAY RECAP ******************************************************************************************
192.168.2.134              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

Step 14 : Namecoin application installed on Windows Client system
Snap 4

Step 15: Create playbook for uninstall namecoin application

root@linuxhelp:~# vi uninstall.yml
- hosts: windows
  gather_facts: true
  tasks:
  - name: Uninstall namecoin
    win_chocolatey:
      name: namecoin
      state: absent
~

Step 16: Check the syntax of the uninstall.yml ansible playbook by using the following command

root@linuxhelp:~# ansible-playbook uninstall.yml --syntax-check

playbook: removeproxy.yml

Step 17: Run the uninstall.yml playbook by using the following command

root@linuxhelp:~# ansible-playbook uninstall.yml 

PLAY [windows] **************************************************************************************

TASK [Gathering Facts] ******************************************************************************
ok: [192.168.2.134]

TASK [Uninstall namecoin] ***************************************************************************
changed: [192.168.2.134]

PLAY RECAP ******************************************************************************************
192.168.2.134              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Step 18: Namecoin application Uninstalled on Windows Client system
Snap 5

With this installation of an application on Windows by using Ansible comes to an end

Всем привет.

Сегодня инсталлируем софт с помощью Ansible. В качестве управляемых хостов берем Windows. Итак, я знаю четыре способа как это сделать: из пакета, прямо из интернета, и с помощью пакетного cmd-файла или PowerShell. В двух последних случаях надо предварительно закинуть на хост сам cmd-файлик или ps1.

Создаем плейбук Ansible.

— name: Windows file example playbook

  hosts: all

  gather_facts: false

Далее пишем наши задачи. Первый вариант — инсталляция из пакета: 

  tasks:

— name: Install package 

    win_package:

      path: c:\temp\install\rdcman.msi

      product_id: ‘{0240359E-6A4C-4884-9E94-B397A02D893C}’

      arguments: /silent /unattended

      state: present

Пусть вы желаете раскрутить Adobe Acrobat Reader на штатных хостах Windows, вы можете воспользоваться модулями win_copy или win_get_url для распространения надлежащего установщика, а затем своим модулем win_package для его установки. Однако можно использовать более изящный способ:

— name: Install Acrobat Reader

  win_chocolatey:

    name: adobereader

    state: present

Что касается вариантов пакетного cmd-файла или PowerShell, то для начала создаем предварительно отдельную папку, если не хотим использовать ту же c:\temp (Вдруг она не существует?)

   — name: Create a directory using cmd.exe

      win_shell: mkdir C:\MasteryCMD

      args:

        executable: cmd    

ИЛИ

   — name: Create a directory using PowerShell

      win_shell: New-Item -Path C:\MasteryPS -ItemType Directory

далее копируем наш master.cmd на целевой хост:

    — name: Copy across a test file

      win_copy:

        src: ~/src/mastery/master.cmd

        dest: ‘C:\MasteryCMD\master.cmd’

и запускаем его на выполнение:

   — name: Create a directory using cmd.exe

      win_shell: C:\MasteryCMD\master.cmd

      args:

        executable: cmd    

С PowerShell поступаем аналогично.

Удачи.

  • Ansi и windows 1251 это одно и тоже
  • Answer the questions to the text windows
  • Anselsdk64 dll скачать для windows 11
  • Anny deck скачать для windows
  • Anno 1701 для windows 10