Ansible как установить на windows 10

Речь в заметке пойдет о запуске Linux приложений под Windows 10 с помощью WSL без виртуальной машины, средствами Windows. Предыстория У нас, в компании Кузбасс-ЦОТ, есть программный продукт “Комплекс”. Это такая штука, которая обучает и тестирует людей, вычисляет их компетентность и прогнозирует риски. Сам продукт представляет собой сервер, написаный на языке PHP, и клиент на Qt5, работающий на вандалоустойчивом терминале с ОС Ubuntu. Есть проблема в следующем: при внедрении ПО на предприятии заказчика, количество этих терминалов может достигать десятки штук, а то и сотню. Приходится объезжать места физической установки терминалов и вручную накатывать образ через Clonezilla, далее конфигурировать его, указывать IP адрес сервера. Так как терминалы поставляются уже с предустановленной ОС, данную проблему я решил исправить с помощью Ansible. Если просто, это такая система управления конфигурациями, где состояние конечной системы описывается в файлах формата YAML и далее это состояние поддерживается.

Речь в заметке пойдет о запуске Linux приложений под Windows 10 с помощью WSL без виртуальной машины, средствами Windows.

Предыстория

У нас, в компании Кузбасс-ЦОТ, есть программный продукт “Комплекс”. Это такая штука, которая обучает и тестирует людей, вычисляет их компетентность и прогнозирует риски. Сам продукт представляет собой сервер, написаный на языке PHP, и клиент на Qt5, работающий на вандалоустойчивом терминале с ОС Ubuntu.

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

Описание решения

Хотя Ansible и написан на Python, установить его через pip, как рассказывается в документации, не получилось, так как требовались возможности Linux.

Ставить второй системой Linux или запускать его в виртуальной машине мне очень не хотелось. Поэтому я пошел по пути меньшего сопротивления и решил использовать WSL. Это подсистема Windows для Linux, позволяющая запускать много программ и утилит без виртуализации. Оговорюсь — это не полноценный Linux, а лишь только реализация окружения и утилит.

Установка WSL

Для установки WSL требуется включить компонент Подсистема Windows для Linux. Откройте PowerShell с правами администратора и выполните команду, включающую данный компонент:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

Далее потребуется перезагрузить компьютер.

Теперь установите через Microsoft Store необходимый дистрибутив Linux. Полный список доступных дистрибутивов можно посмотреть по ссылке. Для себя я выбрал Ubuntu 18.04 LTS.

После установки и запуска, откроется терминал с приглашением указать имя пользователя и пароль для данного дистрибутива. Пароль можно не указывать, пустые пароли пропускает. WSL установлена!

Установка Ansible

Далее я следовал документации по установке Ansible для Ubuntu:

$ sudo apt update
$ sudo apt install software-properties-common
$ sudo apt-add-repository --yes --update ppa:ansible/ansible
$ sudo apt install ansible

Ansible установлен! Теперь можно работать с ним из системы Windows 10:

PS C:Usersivans> wsl ansible
usage: ansible [-h] [--version] [-v] [-b] [--become-method BECOME_METHOD]
               [--become-user BECOME_USER] [-K] [-i INVENTORY] [--list-hosts]
               [-l SUBSET] [-P POLL_INTERVAL] [-B SECONDS] [-o] [-t TREE] [-k]
               [--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER]
               [-c CONNECTION] [-T TIMEOUT]
               [--ssh-common-args SSH_COMMON_ARGS]
               [--sftp-extra-args SFTP_EXTRA_ARGS]
               [--scp-extra-args SCP_EXTRA_ARGS]
               [--ssh-extra-args SSH_EXTRA_ARGS] [-C] [--syntax-check] [-D]
               [-e EXTRA_VARS] [--vault-id VAULT_IDS]
               [--ask-vault-pass | --vault-password-file VAULT_PASSWORD_FILES]
               [-f FORKS] [-M MODULE_PATH] [--playbook-dir BASEDIR]
               [-a MODULE_ARGS] [-m MODULE_NAME]
               pattern
ansible: error: too few arguments

Командой wsl можно вызывать команды WSL из PowerShell в требуемой директории не запуская приложение. Например так можно установить и запустить редактор nano:

wsl sudo apt install nano
wsl nano

Думаю данная заметка пригодится вам, спасибо за прочтение. Буду рад, если поделитесь статьей с коллегами разработчиками.

Ansible in Windows 10

  • Run Ansible in Windows 10

Install the Windows Subsytem for Linux

  • Installation Guide for Windows 10.
  • Install Ubuntu 18.04 LTS

Check Ubuntu Version

Install Ansible in Windows Subsystem

  • Installation Guide for Ubuntu

Ansible Installation

$ sudo apt-get update && sudo apt-get install software-properties-common -y
$ sudo apt-add-repository universe -y
$ sudo apt-add-repository ppa:ansible/ansible -y
$ sudo apt-get update && sudo apt-get install ansible python-pip -y

Python library for Windows Remote Management Installation

  • Ansible uses the pywinrm package to communicate with Windows servers over WinRM. It is not installed by default with the Ansible package, but can be installed by running the following:
$ pip install "pywinrm>=0.3.0" 
$ pip install cryptography

Check Ansible Version

$ ansible --version
$ ansible-playbook --version

Install Code Insiders — Optional

  • Download Code Insider and Install

Windows Client Configuration

PowerShell in Administrator Mode

Settings -> Network & Internet -> Change Connection Properties -> Network Profile -> Private

PS > Enable-PSRemoting
PS > Get-Service | Where-Object {$_.Name -eq "WinRM"}
PS > Start-Service WinRM
PS > Set-Item -Path WSMan:localhostServiceAuthBasic -Value $true
PS > winrm quickconfig

Configure a Windows host for remote management with Ansible

PS > $PSVersionTable.PSVersion
PS > .scriptsConfigureRemotingForAnsible.ps1

Windows Modules

Ping

$ ansible aviservers -m win_ping
  • If ansible.cfg is configured in non NTFS file system, no need of adding inventort parameter, can run the below command.
$ ansible aviservers -m win_ping

Get System Information

$ ansible aviservers -m setup

Execute plain commands

$ ansible aviservers -m raw -a "dir"
$ ansible aviservers -m raw -a "ipconfig" 

Execute service related commands

$ ansible aviservers -m win_service -a name="spooler"
$ ansible aviservers -m win_service -a "name=spooler state=stopped"
$ ansible aviservers -m win_service -a "name=spooler state=started"

Execute feature related commands

$ ansible aviservers -m win_feature -a "name=Telnet-Client state=present"

Run Playbooks

$ ansible-playbook playbooks/local/test.yml
$ ansible-playbook playbooks/config/ipconfig.yml
$ ansible-playbook playbooks/config/stats.yml
$ ansible-playbook playbooks/config/ping.yml
$ ansible-playbook playbooks/scripts/powershell.yml
$ ansible-playbook playbooks/user/create.yml
$ ansible-playbook playbooks/iis/enable.yml
$ ansible-playbook playbooks/packages/install/rdcm.yml
$ ansible-playbook playbooks/packages/uninstall/rdcm.yml
$ ansible-playbook playbooks/packages/install/firefox.yml
$ ansible-playbook playbooks/packages/uninstall/firefox.yml

Issues

  • The specified module ‘ServerManager’ was not loaded because no valid module file was found in any module directory.

    • Install Remote Server Administration Tools for Windows 10.
    PS > Import-Module ServerManager
    PS > Get-WindowsFeature

Known Issues

  • win_feature module will work only in Windows Server edition.

Ubuntu Components for Ansible Kerberos Authentication

$ sudo apt-get update && sudo apt-get install software-properties-common -y
$ sudo apt-get install gcc python-dev libkrb5-dev
$ sudo apt-get install python3-pip
$ sudo apt-get install python-pip
$ python3 -m pip install --upgrade pip
$ sudo -H pip install virtualenv
$ sudo -H pip install pywinrm[kerberos]
$ sudo apt install krb5-user
$ sudo pip install pywinrm
$ sudo pip install ansible

Configuring Ubuntu for Kerberos Authentication with Active Directory

Kerberos Server Guide

  • Kerberos Server Guide

Ansible Vault

$ ansible-vault create group_vars/aviservers/aviservers.yml
$ ansible-vault encrypt group_vars/aviservers/aviservers.yml

Edit Encypted File

$ ansible-vault edit group_vars/aviservers/aviservers.yml

View Encypted File

$ ansible-vault view group_vars/aviservers/aviservers.yml

Decrypt File

$ ansible-vault decrypt group_vars/aviservers/aviservers.yml

Run the playbooks with ecryption

  • Update vault_password_file
$ touch /secret/vault
$ ansible-vault edit group_vars/aviservers/aviservers.yml
$ ansible-playbook playbooks/config/ping.yml
$ ansible-playbook playbooks/config/ping.yml --vault-password-file /etc/ansible/secret/vault
$ ansible-playbook playbooks/config/ping.yml --ask-vault-pass 

Setting the Ansible Vault Editor

Ansible Galaxy

$ cd playbooks/roles/
$ ansible-galaxy init iis --offline

Do you want to test or start learning Ansible and you have only Windows 10?
Following steps will help you to install and configure Ansible in Windows Subsystem for Linux.

Here, I have to make a disclaimer: all bellow information is already available in one form or another if you google it; what I’ve done is to make my own recipe and I hope, dear reader, you’ll like it.

So let’s get started!

What is Windows Subsystem for Linux (WSL) and how to install it

Windows Subsystem for Linux (WSL) is a compatibility layer for running Linux binary executables (in ELF format) natively on Windows 10 and Windows Server 2019. In May 2019, Microsoft has announced WSL2, introducing a real Linux kernel through a subset of Hyper-V features. WSL 2 will be available in Windows 10 builds 18917 (20H1) or higher. My Windows 10 build is 18363 (19H2) so we’ll use WSL.

So, WSL installation consists in 2 steps:

1. Enable WSL feature

Microsoft documentation is clear about this: open PowerShell as Administrator, run the command and reboot:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

2. Install Linux Distribution from Microsoft Store

Open Microsoft Store and search for linux. Don’t ask about language. I have set it English but I am located in a region with default French.

I choose Ubuntu 18.04 LTS. After download you can launch it:

Installation is straightforward:

When finished, you’ll be asked for initial user and password. You can also reset the root password with a secure one:

Install Ansible

Now it is time to install Ansible packages. For more info you can check Ansible documentation; I have added the commands needed for Windows connectivity via WinRM:

$ sudo apt update
$ sudo apt install software-properties-common
$ sudo apt-add-repository --yes --update ppa:ansible/ansible
$ sudo apt install ansible
$ sudo apt install python-pip
$ pip install pywinrm

A summary of commands used:

Configure WinRM on Windows to use it with Ansible

WinRM is a management protocol used by Windows to remotely communicate with another server and is included in all recent Windows operating systems. Since Windows Server 2012, WinRM has been enabled by default, but we need extra configuration to use WinRM with Ansible.

There’s a Configure Remoting for Ansible script you can run on the remote Windows machine (in a PowerShell console as an Admin) to turn on WinRM and set up a https listener.

After running the script, check WinRM listeners with following command:

winrm enumerate winrm/config/Listener  

The result should look like:

When connecting to a Windows host, there are several different options that can be used for authenticating with an account. These are detailed well in Ansible documentation.

I choose certificate authentication which uses certificates as keys similar to SSH key pairs; for this I create on windows a local account, dedicated to Ansible:

Then, we need a certificate associated to this user. We can use different methods to create a certificate. I will use PowerShell:

# Set the name of the local user that will have the key mapped
$username = "ansibleusr"
$output_path = "C:tempscripts"

# Instead of generating a file, the cert will be added to the personal
# LocalComputer folder in the certificate store
$cert = New-SelfSignedCertificate -Type Custom `
    -Subject "CN=$username" `
    -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2","2.5.29.17={text}upn=$username@localhost") `
    -KeyUsage DigitalSignature,KeyEncipherment `
    -KeyAlgorithm RSA `
    -KeyLength 2048

# Export the public key
$pem_output = @()
$pem_output += "-----BEGIN CERTIFICATE-----"
$pem_output += [System.Convert]::ToBase64String($cert.RawData) -replace ".{64}", "$&`n"
$pem_output += "-----END CERTIFICATE-----"
[System.IO.File]::WriteAllLines("$output_pathcert.pem", $pem_output)

# Export the private key in a PFX file
[System.IO.File]::WriteAllBytes("$output_pathcert.pfx", $cert.Export("Pfx"))

We will convert now the PFX file to a pem and private key that pywinrm can use, with the following command with OpenSSL:

# openssl pkcs12 -in cert.pfx -clcerts -nokeys -out cert.pem
# openssl pkcs12 -in cert.pfx -nocerts -nodes -out cert_key.pem

Once a certificate has been generated, we need to import the issuing certificate into the Trusted Root Certificate Authorities of the LocalMachine store, and the client certificate public key must be present in the Trusted People folder of the LocalMachine store. For this example, both the issuing certificate and public key are the same.

$cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import("cert.pem")

$store_name = [System.Security.Cryptography.X509Certificates.StoreName]::Root
$store_location = [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine
$store = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList $store_name, $store_location
$store.Open("MaxAllowed")
$store.Add($cert)
$store.Close()

For public key, the code:

$cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import("cert.pem")

$store_name = [System.Security.Cryptography.X509Certificates.StoreName]::TrustedPeople
$store_location = [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine
$store = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList $store_name, $store_location
$store.Open("MaxAllowed")
$store.Add($cert)
$store.Close()

Then, we map the certificate to the local user account:

$username = "ansibleusr"
$password = ConvertTo-SecureString -String "password" -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password

# This is the issuer thumbprint which in the case of a self generated cert
# is the public key thumbprint, additional logic may be required for other
# scenarios
$thumbprint = (Get-ChildItem -Path cert:LocalMachineroot | Where-Object { $_.Subject -eq "CN=$username" }).Thumbprint

New-Item -Path WSMan:localhostClientCertificate `
    -Subject "$username@localhost" `
    -URI * `
    -Issuer $thumbprint `
    -Credential $credential `
    -Force

Certificate authentication is not enabled by default, we will enable by running the following in PowerShell:

Set-Item -Path WSMan:localhostServiceAuthCertificate -Value $true

Finally, we need now to copy the certificate to Ansible configuration folder. From Windows side we can access linux file system from WSL with:

\wsl${distro name}

where {distro name} is the name of a running distro.

Finishing configuration on Ansible side and test connection

As already mentioned above, there are several different options that can be used when authenticating with an account. The authentication type may be set on inventory hosts or groups with the ansible_winrm_transport variable.

On WSL side, we edit /etc/ansible/hosts file with command

# sudo nano /etc/ansible/hosts

and we add following lines:

[myhost]
127.0.0.1

[myhost:vars]
ansible_connection = winrm
ansible_winrm_cert_pem = /etc/ansible/cert.pem
ansible_winrm_cert_key_pem = /etc/ansible/cert_key.pem
ansible_wirm_transport = certificate
ansible_winrm_server_cert_validation = ignore

The line ansible_winrm_server_cert_validation = ignore is needed because we are using self-signed certificates and there is no CA to validate our certs.

Also, notice 127.0.0.1 as myhost. Windows and WSL are sharing the same network configuration.

Now we can test the connection:

Conclusion

Next step is to create playbooks and test Ansible. Happy automation!

Steps to install Ansible on Windows 10.

First we need to enable Windows Subsystem for Linux (Beta) which is an Ubuntu linux on Windows. Complete the steps in this blog:

Enable Linux subsystem on Windows

<<<NEXT STEPS>>>

Install Ansible Latest Releases Via Apt (Ubuntu)

To configure the PPA on your machine and install ansible run these commands:

$ sudo apt-get update
$ sudo apt-get install software-properties-common
$ sudo apt-add-repository ppa:ansible/ansible
$ sudo apt-get update
$ sudo apt-get install ansible

To install Ansible on Centos 7 use command:  $ yum install ansible

After the Ansible install check basic things:

# ansible –version

ansible 2.6.3
config file = /etc/ansible/ansible.cfg
configured module search path = [u’/root/.ansible/plugins/modules’, u’/usr/share/ansible/plugins/modules’]
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Jul 13 2018, 13:06:57) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]

The windows drives are mounted in the Subsystem inside the /mnt directory

Open a bash prompt, and cd into your Windows user’s Documents directory:

$cd /mnt/c/Users/youruserid/Documents/

Create a new test playbook:

$ vim test.yml

Add the following contents (note the — should start at column 1):

  ---

   - hosts: localhost
     tasks:
     - debug: msg="Ansible is working!"

Run the playbook with the command

$ ansible-playbook test.yml –connection=local

[WARNING]: Could not match supplied host pattern, ignoring: all

[WARNING]: provided hosts list is empty, only localhost is available

PLAY [localhost] *************************************************************************************

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

TASK [debug] ***********************************************************************************************************ok: [localhost] => {

“msg”: “Ansible is working!”

}

PLAY RECAP *************************************************************************************************************localhost                  : ok=2    changed=0    unreachable=0    failed=0

This indicates that Ansible was successfully installed and you can start using it.

EXAMPLES:

Add the following servers in the /etc/ansible/hosts file so ansible can find the servers to run the commands on:

[cdhservers]

10.x.x.1

10.x.x.2

10.x.x.3

10.x.x.4

Create a playbook file pb1.yml with below lines:

---
  - hosts: cdhservers
    tasks:
      - name: DISKSPACE
        shell: df -h
        register: out1
      - debug: var=out1.stdout_lines

      - name: CPU/RAM
        shell: vmstat -w 3 3
        register: out2
      - debug: var=out2.stdout_lines

      - name: FREEMEM
        shell: free -h
        register: out3
      - debug: var=out3.stdout_lines

Run this using the command which will show the output below:

$ ansible-playbook pb1.yml -u root -k

SSH password:

PLAY [cdhservers] *************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************************************************************************************************************************
ok: []
TASK [DISKSPACE] *************************************************************************************
changed: []

TASK [debug] *************************************************************************************
ok: [] => {
“out1.stdout_lines”: [
“Filesystem Size Used Avail Use% Mounted on”,
“/dev/mapper/vg_trhel6-lv_root”,
” 250G 93G 155G 38% /”,
“tmpfs 7.8G 0 7.8G 0% /dev/shm”,
“/dev/sda1 477M 105M 348M 24% /boot”,
“cm_processes 7.8G 43M 7.8G 1% /var/run/cloudera-scm-agent/process”
]
}

TASK [CPU/RAM] *************************************************************************************
changed: []

TASK [debug] *************************************************************************************
ok: [] => {
“out2.stdout_lines”: [
“procs ———–memory———- —swap– —–io—- –system– —–cpu—–“,
” r b swpd free buff cache si so bi bo in cs us sy id wa st”,
” 7 0 445172 554660 209108 4151844 0 0 29 92 3 1 7 1 91 0 0t”,
” 0 0 445172 553932 209108 4151972 0 0 0 693 3774 12904 3 1 96 0 0t”,
” 0 0 445172 553088 209108 4152268 0 0 0 4 5641 16558 8 2 89 0 0t”
]
}

TASK [FREEMEM] *************************************************************************************
changed: []

TASK [debug] ***********************************************************************************************************************************************************************************************************************************
ok: [] => {
“out3.stdout_lines”: [
” total used free shared buffers cached”,
“Mem: 16333920 15779352 554568 83820 209108 4152180”,
“-/+ buffers/cache: 11418064 4915856”,
“Swap: 2097148 445172 1651976”
]
}

EXAMPLE: ping the servers

ansible -m ping cdhservers -u root -k

EXAMPLE:Change a users password

$ansible all -m shell -a “echo passwordxxx | passwd –stdin useridxxx” -u root -k

SSH password:

| SUCCESS | rc=0 >>

Changing password for user useridxxx.

passwd: all authentication tokens updated successfully.

Reference:

https://www.jeffgeerling.com/blog/2017/using-ansible-through-windows-10s-subsystem-linux

Like this post? Please share to your friends:
  • Anselsdk64 dll скачать для windows 10 x64
  • Another installation is in progress windows
  • Anno 2205 не запускается на windows 10 висит в процессах
  • Anno 1800 не запускается на windows 10 без ошибок
  • Anno 1800 вылетает без ошибки на windows 10