Ansible playbook install windows

How to install Ansible on Windows?

Love Ansible, but wondering how to get it running on Windows?

Ansible is one of the most popular configuration administration and infrastructure automation tools. It helps to automate infrastructure configuration/provisioning, software deployments, and general infrastructure management.

Ansible was initially available on Linux. However, with Microsoft’s new viewpoint on open source, their community improvements, and their acceptance of a more agile, DevOps-minded software development method, Windows support is gradually catching up the pace.

Although Windows support requires a slight bit more configuration, it’s not very bad once the initial setup is done. There are two possible ways to get it installed.

Using Cygwin

Have you heard of Cygwin?

It is a POSIX-compatible environment to run on Windows. Means – you can run many things on Windows, which you usually do on UNIX-based OS.

If its the first time you heard about Cygwin then I would refer to their official website to get more understanding.

The default Cygwin installation doesn’t cover Ansible. Hence, you got to select them during installation, as explained below manually.

  • Download Cygwin (Chose 32 bit or 64 bit Cygwin package as per your system)

  • Run the Cygwin installation file which you downloaded above and follow the screen.

  • Select download source as “Install from Internet.”

  • Set a root directory where you would like your application installed

  • Select a directory where you would like to install your Cygwin packages

  • Select Direct connection if you’re not using a proxy.

  • Select a mirror to download your packages. You can choose any from the list.

  • Packages available for installation will be shown; this is where we have to select ansible – select view as Full explicitly and then search for “ansible” and then select the latest version as shown below.
  • Ansible-doc is optional, click next

  • Review and confirm changes by clicking next

  • It will download and install the necessary packages.

  • Once done, you will get a success message, click Finish

Congratulation! You have installed Cygwin with Ansible on Windows. Let’s verify it.

  • Double click on Cygwin Terminal icon from the desktop and type ansible —version

And, as you can see, it has successfully installed.

Go ahead and play around with it. If you are interested in learning Ansible, then check out this Udemy course.

Using Ubuntu on Windows 10

Thanks to Microsoft. Now it is possible to install Ubuntu on Windows 10.

Let’s get it started.

  • Search for Windows features in the search box. And when the “Turn Windows features on or off ” appears, click on that.
Читайте также:  Флешка не открывается что делать windows 10

  • A window will open with a bunch of features. Scroll down and check the box of Windows Subsystem for the Linux option. And after that, click on the OK button.

  • Open the Microsoft Store and search for Ubuntu to install the latest version.

  • After the installation, you will see a launch button, use that to open the Ubuntu bash.
  • On Ubuntu bash, it will ask you to set the username and password for the default user. You can also set the root account password from here by typing sudo passwd root

  • Its time to get the Ansible installed with the following commands.
  • Press Y when it asks for…

After the installation, let’s test whether by creating and running a demo playbook.

  • Create a file called testbook.yml
  • Add the following lines and save the file

And, finally, run the playbook.

Conclusion

I hope this helps you to install Ansible on Windows. Check out this blog post to learn about the playbook to automate the tasks.

📜 9 Ansible плейбуков примеров для администрирования Windows

Я предполагаю, что вы уже установили Ansible на Windows и вы хотите управлять серверами Windows.

Ниже приведены некоторые из наиболее часто используемых задач, выполняемых администраторами Windows ежедневно. Вы будете удивлены, увидев, как легко администрируется Windows с помощью Ansible.

IP-адрес моего компьютера с контроллером Ansible Windows – 192.168.0.106, а IP-адрес моей удаленной системы Windows – 192.168.0.102

Мое соединение с удаленным хостом прошло успешно.

Копирование файлов

win_copy – это модуль, который копирует файл с локального сервера на удаленный хост Windows.

Я буду использовать этот модуль для копирования одного PDF.

Используйте приведенный ниже код YAML, укажите исходный и целевой путь.

Установить / удалить MSI

state present означает, что MSI будет установлен на машине, и приложение будет находится в текущем состоянии.

Здесь я устанавливаю Apache.

Теперь перейдите в систему Windows и проверьте, успешно ли установлено приложение apache.

Ниже приведен тот же пример, что и выше, но вместо state мы используем аргумент install для установки apache.

Чтобы удалить приложение с помощью файла MSI, вам нужно использовать модуль win_package.

Отсутствие state absent, что приложение будет удалено с использованием файла MSI.

Здесь я удаляю Apache.

Запустите ansible плейбук для удаления MSI

Теперь, если я проверю версию apache, я получу следующий вывод, так как приложение было удалено.

Удалить программное обеспечение (.EXE)

Вы также можете удалить программное обеспечение с помощью файла .exe, используя идентификатор продукта этого программного обеспечения (product id).

Остановить / запустить / перезапустить службу Windows

Модуль win_service используется для запуска, остановки или перезапуска службы. Здесь я покажу вам, как остановить службу tomcat.

Запустите ansible плейбук, чтобы остановить службу Tomcat.

Сбор фактов

С помощью модуля ansible win_disk_facts вы можете получить всю информацию о диске целевого хоста.

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

Запуск команд

Какие бы команды вы ни выполняли в Windows, они могут выполняться через модуль ansible win_command.

Вам просто нужно указать команду в вашем файле YAML.

На примере я просто создаю каталог.

Переменные среды

Система Windows имеет несколько переменных среды, например, JAVA_HOME.

Читайте также:  Что такое linux header

Используя ANSI-модуль win_environment, вы можете добавлять или изменять переменные среды в системе Windows.

В этом примере я добавляю новую переменную в список переменных среды Windows.

Изменить реестр

Ansible модуль win_regedit используется для добавления или редактирования данных реестра на удаленной машине с Windows.

Вам необходимо указать путь к реестру и контент для добавления / обновления.

Здесь я создаю новую запись реестра Itisgood по пути HKLM:\SOFTWARE, а затем добавляю имя и данные в этот реестр.

Запустите ansible плейбук, чтобы добавить именения в реестр.

Удаление логов

Модуль win_eventlog используется для добавления, очистки или удаления логов системы Windows.

Перейдите в Windows Powershell и перечислите EventLogs, присутствующие на удаленном компьютере с Windows.

Теперь, если вы снова перечислите логи, вы увидите, что логи Internet Explorer были удалены.

Добавить комментарий Отменить ответ

• Свежие записи

• Категории

• itsecforu.ru

• Страны посетителей

IT is good

9 Ansible Playbooks Example for Windows Administration

I will show you several operations which an administrator can perform on a remote windows system using ansible-playbook.

Ansible is one of the most used DevOps tools in the market today. It provides a bunch of windows modules that are used to configure and manage the Windows server. I assume you already have Ansible installed on Windows from where you want to manage the Windows servers.

The following are some of the commonly used tasks performed by Windows administrators on a daily basis. You will be amazed to see how easy it is administered Windows using Ansible.

My Ansible Windows controller machine’s IP address is 192.168.0.106, and my remote Windows system’s IP address is 192.168.0.102. Before you get started, make sure you run a win_ping module to check whether you are able to connect to windows remote server or not.

My connection to a remote host is successful.

So, let’s get started with Ansible Playbooks…

Copying Files

win_copy is an ansible module that copies a file from the local server to a remote Windows host. I will use this module to copy a single PDF.

Use the below YAML code, give the source and destination paths.

Run the ansible-playbook for win_copy.

The file has been copied successfully at the destination location on a remote windows system.

Install/UnInstall MSI

To install an application using the MSI file, you need to use win_get_url to mention the path of the MSI file to download and then use the win_package module to install it. The state present means the MSI will be installed on the machine, and the application is in the present state.

Here, I am installing Apache.

YAML code to be used:

Run the ansible-playbook to install using MSI.

Now, go to the windows system and check if the apache application got installed successfully.

You can also install applications using MSI with arguments. Below is the same example as above, but instead of a state, we are using an install argument to install apache.

YAML code to be used:

To uninstall an application using the MSI file, you need to use the win_package module. The state absent means the application will be uninstalled using the MSI file.

Читайте также:  Stamp для windows 10

Here, I am uninstalling Apache.

Run the ansible-playbook to uninstall using MSI.

Now, if I check the apache version, I will get the below output as the application got uninstalled.

Uninstall Software (.EXE)

You can also uninstall software with .exe file using the product id of that software.

Run the ansible-playbook to uninstall 7-Zip.

Stop/Start/Restart Windows Services

win_service ansible module is used to start, stop, or restart a service. Here, I will show you how to stop the tomcat service.

You need to mention the service name in the YAML file and set the state to stop.

Run the ansible-playbook to stop the tomcat service.

If you check the tomcat service on the windows system, it is now in stopped status.

You can define state to started or restarted or paused to change the status of the service.

Gathering Facts

Using win_disk_facts ansible module, you can retrieve all the disk information of the target host.

Run the ansible-playbook to get the disk information.

Using win_command ansible module, you can execute commands on the remote host and get CPU information, device details, and much more.

Run the ansible-playbook to get remote system information.

Running Commands

Whatever commands you run on a window, they can be run through the ansible win_command module. You just need to specify the command in your YAML file. Here, I am just creating a directory.

Run the ansible-playbook to perform win_command operation.

Environment Variables

A windows system has multiple environment variables, for example, JAVA_HOME. Using the win_environment ansible module, you can add or modify environment variables on a windows system. In this example, I am adding a new variable to the windows environment variables list.

Run the ansible-playbook to add the environment variable on a remote windows machine.

Go to the environment variables window; you will see the new variable you just added is present here.

Add/Edit Registry

win_regedit ansible module is used to add or edit registry details on a remote windows machine. You need to give the path of the registry and content to be added/updated. Here I am creating a new registry entry GeekFlare inside HKLM:\SOFTWARE path and then adding name and data to this registry.

Run the ansible-playbook to add the registry.

If you go to Registry Editor on the remote system, you can see this registry has been added successfully with Name and Data parameters.

Delete Log

win_eventlog ansible module is used to add, clear, or remove windows event logs from the windows system.

Go to Windows Powershell, and list the EventLogs present on the remote windows machine.

Now, I will show how to remove logs from all sources for Internet Explorer.

Run the ansible-playbook to remove the Internet Explorer form the remote windows machine.

Now, if you list the EventLogs again, you will see Internet Explorer logs have been removed.

So, that was all about Ansible playbooks, which can be used for remote windows administration. Go ahead and try out these playbooks. You can also try other Ansible Windows modules available.

Оцените статью