Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Configuring Ansible for Linux and Windows Host Management

Tech May 16 4

Ansible Installation and Basic Usage

Ansible is a powerful automation engine for configuration management, application deployment, task automation, and orchestration. This guide covers its installation, core functionalities, and specific setup for managing both Linux and Windows target hosts.

Installation on Linux Control Node

To begin, install Ansible on your Linux control machine. The installation process varies slightly depending on your distribution.

For RHEL/CentOS Systems:

Ansible is available through the Extra Packages for Enterprise Linux (EPEL) repository.

$ sudo yum install epel-release
$ sudo yum install ansible

For Debian/Ubuntu Systems:

Ansible can be installed directly from the official repositories.

$ sudo apt update
$ sudo apt install ansible

Key Ansible Components

Once installed, several core Ansible components are available on your system. You can inspect the installed files:

$ rpm -ql ansible
# Or for Debian/Ubuntu: dpkg -L ansible

Common directories and executables include:

  • /etc/ansible/: Main configuration directory.
  • /etc/ansible/ansible.cfg: The primary Ansible configuration file.
  • /etc/ansible/hosts: The default inventory file, defining managed nodes.
  • /usr/bin/ansible: The main command-line tool for ad-hoc commands.
  • /usr/bin/ansible-playbook: Used to run Playbooks.
  • /usr/bin/ansible-galaxy: For managing Ansible roles.
  • /usr/bin/ansible-vault: For encrypting sensitive data.

Verifying Installation

After installation, you can verify Ansible's functionality by attempting to ping all hosts defined in your inventory (or localhost if no inventory is set up yet):

$ ansible all -m ping

By default, Ansible performs SSH host key checking, which can prompt for confirmation on first connection. To disable this for convenience (especially in development or controlled environments), modify your /etc/ansible/ansible.cfg file:

[defaults]
host_key_checking = False

Common Ad-Hoc Commands with Modules

Ansible uses modules to perform tasks on managed nodes. Here are examples of commonly used modules for ad-hoc commands.

copy Module: Transferring Files and Directories

To copy a file from the control node to a remote server:

$ ansible webservers -m copy -a 'src=~/local_file.txt dest=/opt/remote_path/remote_file.txt mode=0644'

When copying directories, Ansible's behavior depends on the destination path:

  • If dest specifies a non-existent directory name (e.g., dest=/tmp/new_dir) and src is /etc/source_dir, the source directory will be copied and renamed to /tmp/new_dir.
  • If dest specifies an existing directory (e.g., dest=/tmp/existing_dir) and src is /etc/source_dir, the source directory will be copied into the destination, resulting in /tmp/existing_dir/source_dir.

Example of copying a directory:

$ ansible all -m copy -a 'src=/etc/ansible/roles dest=/tmp/ansible_roles_backup'

To copy a file with specific permissions, owner, and group (requires become if target user is not the connection user):

$ ansible database_servers -m copy -a "src=/opt/my_app/config.ini dest=/etc/my_app/config.ini mode=0600 owner=dbadmin group=dbusers" --become

shell Module: Executing Commands

The shell module executes commands on remote hosts, similar to directly typing them in a shell. Remember to escape special characters like $.

$ ansible webservers -m shell -a 'cat /etc/passwd | grep "john_doe"'
$ ansible samba_clients -m shell -a "sed -i '\$d' /etc/fstab"

yum/apt Modules: Package Management

To install or manage packages using the appropriate package manager:

$ ansible all -m yum -a 'name=nginx state=latest' # For RHEL/CentOS
$ ansible all -m apt -a 'name=apache2 state=latest' # For Debian/Ubuntu

script Module: Executing Local Scripts Remotely

The script module allows you to run a script located on your control node directly on the remote hosts without explicitly copying it first.

$ ansible all -m script -a '/path/to/local_script.sh'

Privilege Escalation (become)

For tasks requiring root or another user's privileges, Ansible uses the become directives. The older --sudo parameter is deprecated in favor of --become.

To execute a command with elevated privileges:

$ ansible etcd_nodes -m shell -a "systemctl status etcd" --become --become-method=sudo --become-user=root

You can configure become settings in /etc/ansible/ansible.cfg under the [privilege_escalation] section, or specify them per command as shown above.

When using --ask-pass (or -k), Ansible will prompt for the SSH password for the remote user. This is often used when SSH key are not configured for passwordless access:

$ ansible etcd_nodes -m shell -a "systemctl status etcd" -k

Managing Windows Hosts with Ansible

Ansible can effectively manage Windows servers, but it requires a different communication protocol (WinRM) and specific configurations on both the Linux control node and the Windows target.

Ansible Control Node Setup for Windows

Your Linux control node requires the pywinrm Python module to communicate with Windows machines via WinRM.

1. Ensure Python's package manager, pip, is installed:

$ sudo yum install python-pip # For RHEL/CentOS with Python 2
$ sudo apt install python-pip # For Debian/Ubuntu with Python 2
# For Python 3, use python3-pip

2. Install the pywinrm module:

$ pip install pywinrm

3. Configure your inventory file (e.g., /etc/ansible/hosts) for Windows hosts. A typical entry might look like this:

[windows_servers]
192.168.1.105 ansible_connection=winrm ansible_port=5985 ansible_winrm_scheme=http ansible_winrm_server_cert_validation=ignore ansible_user="Administrator" ansible_password="YourPassword"

Note the use of ansible_connection=winrm, the standard WinRM port 5985 (or 5986 for HTTPS), and authentication details. ansible_winrm_server_cert_validation=ignore is often used in development or internal environments to bypass certificate validation.

Windows Target Host Configuration

For Ansible to manage a Windows server, the following prerequisites must be met:

  • .NET Framework 3.0 or higher.
  • PowerShell 3.0 or higher.
  • The WinRM service must be configured and running.
  • PowerShell execution policy set to RemoteSigned or less restrictive.

Here are the steps to configure WinRM on the Windows target:

1. Install .NET Framework 3.0+: Download and install the appropriate .NET Framework version if not already present.

2. Upgrade PowerShell to 3.0+: Many Windows Server OS versions (like 2008 R2) may have PowerShell 2.0 by default. Upgrade to a newer version by installing Windows Management Framework (WMF).

3. Set PowerShell Execution Policy: Open PowerShell as an administrator and execute:

Set-ExecutionPolicy RemoteSigned

4. Configure WinRM Service: Open an elevated PowerShell prompt and run these commands to configure WinRM for basic, unencrypted HTTP communication (suitable for controlled environments).

# Check WinRM listener status (optional)
winrm enumerate winrm/config/listener

# Perform quick configuration to enable WinRM
winrm quickconfig -q

# Allow Basic authentication
winrm set winrm/config/service/auth '@{Basic="true"}'

# Allow unencrypted communication (not recommended for production over public networks)
winrm set winrm/config/service '@{AllowUnencrypted="true"}'

Addressing a Known Bug in PowerShell 3.0 on Windows Server 2008

If you are running Windows Server 2008 with PowerShell 3.0, a known bug related to memory usage in WinRM can prevent Ansible from connecting. A hotfix is available:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$url = "https://raw.githubusercontent.com/jborean93/ansible-windows/master/scripts/Install-WMF3Hotfix.ps1"
$file = "$env:temp\Install-WMF3Hotfix.ps1"
(New-Object -TypeName System.Net.WebClient).DownloadFile($url, $file)
powershell.exe -ExecutionPolicy ByPass -File $file -Verbose

Executing these commands will download and run a script to apply the hotfix, typically requiring a system reboot.

Ansible Modules for Windows

Once your Windows target is configured, you can use specific win_ modules for management tasks.

win_ping Module: Test Connectivity

To verify that Ansible can connect to your Windows host:

$ ansible windows_servers -m win_ping

A successful response will look like:

192.168.1.105 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

win_copy Module: Transfer Files to Windows

To copy files from the Linux control node to a Windows target, remember to use Windows-style paths (e.g., D:\\path\\file.txt, escaping backslashes if needed in a string).

$ ansible windows_servers -m win_copy -a 'src=/home/control_user/my_app.exe dest=D:\\Applications\\my_app.exe'

win_file Module: Manage Files and Directories on Windows

This module allows you to create, delete, or modify file system objects on Windows hosts.

To delete a file:

$ ansible windows_servers -m win_file -a "path=F:\\data\\old_report.log state=absent"

To create a new directory:

$ ansible windows_servers -m win_file -a "path=C:\\ProgramData\\MyApp\\Logs state=directory"

win_shell Module: Execute PowerShell Commands on Windows

Similar to the shell module for Linux, win_shell executes commands on Windows targets, typically PowerShell commands.

$ ansible windows_servers -m win_shell -a 'Get-Service -Name "WinRM" | Select-Object Status, DisplayName'

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.