Integrating PowerShell with Ansible for hybrid automation

Power Duo

Deep Dive into Hybrid Automation

Consider an example in which an organization runs a three-tier application involving a Linux web server, a Windows application server, and a Linux database server. Traditionally, setting up and managing this configuration would involve the use of one set of tools and scripts for the Linux servers and a different set for the Windows server.

With the integration of Ansible and PowerShell, the entire setup can be managed with a single Ansible playbook. The playbook deploys the Linux web server with Ansible's native Linux modules then runs a PowerShell script to configure the Windows application server; finally, it manages the Linux database server, again with the Linux modules.

This single-run orchestration for setting up the environment ensures that the configuration is consistent across all tiers of the application and significantly reduces the risk of misconfiguration or setup errors.

Consider the Ansible playbook in Listing 1. In this example, the first task installs Apache on the web server with the Ansible yum module. The second task configures the application server with a PowerShell script that is run by the win_shell module. The third task installs MySQL on the database server, again with the yum module.

Listing 1

Ansible Playbook

- name: Setup three-tier application
  hosts: all
  tasks:
    - name: Install Apache
      when: "'web' in group_names"
      yum:
        name: httpd
        state: present
    - name: Configure Application Server
      when: "'app' in group_names"
      win_shell: |
        Import-Module ServerManager
        Add-WindowsFeature -Name Web-Server
    - name: Install MySQL
      when: "'db' in group_names"
      yum:
        name: mysql-server
        state: present

Real-World Scenarios

Expanding on the previous scenario, the next solution combines the prowess of Ansible's flexibility and PowerShell's extensive integration with Windows, ensuring that the entire environment, involving both Linux and Windows servers, can be managed from a single platform, significantly improving efficiency.

The following instructions suppose you are an IT administrator managing multiple Windows Server 2019 instances in your infrastructure. Over time, the business has shifted, and now you need to reconfigure these servers to support a web server role with several features enabled. Alongside this, you want to ensure that Internet Information Services (IIS) is set up correctly with the necessary modules.

To begin, you install Ansible on a Linux control machine. Ansible does not run on a Windows control machine. Use your distribution's package manager (e.g., Apt for Ubuntu or Yum for CentOS) and verify the installation by checking the Ansible version:

sudo apt-get install ansible
ansible --version

Now configure Ansible to manage Windows hosts by editing the /etc/ansible/hosts file and adding the Windows hosts. The hosts file is essentially Ansible's inventory file:

[windows]
192.168.1.150
[windows:vars]
ansible_user=admin
ansible_password=secret
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore

Next, set up the Windows host for management by Ansible, which involves enabling Windows Remote Management (WinRM) on the Windows host. This can be done by running a PowerShell script on the Windows host:

$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

Now validate the configuration by pinging the Windows host from the Ansible control machine:

ansible windows -m win_ping

Next, install PowerShell on the Ansible control machine. Some Linux distributions have PowerShell in their standard repositories.

Ansible allows for the installation and configuration of Windows features and roles with the win_feature module. However, for complex configurations such as setting up specific modules on IIS, PowerShell scripts can provide better control. The Ansible playbook in Listing 2 demonstrates this process.

Listing 2

main.yml

- name: Execute PowerShell script for complex management of Windows Server roles and features
  hosts: windows_servers
  tasks:
    - name: Install IIS role and features
      win_feature:
        name:
          - Web-Server
          - Web-WebServer
          - Web-Common-Http
          - Web-Default-Doc
          - Web-Dir-Browsing
          - Web-Http-Errors
          - Web-Static-Content
        state: present
        include_sub_features: yes
        include_management_tools: yes
    - name: Run PowerShell script for complex IIS configuration
      win_shell: |
        # Import the WebAdministration module to manage IIS
        Import-Module WebAdministration
        # Set the default document for the website
        Set-WebConfigurationProperty -Filter "/system.webServer/defaultDocument" -Name "files" -Value @{value='index.html'} -PSPath 'IIS:\Sites\Default Web Site'
        # Enable dynamic content compression
        Set-WebConfigurationProperty -Filter "/system.webServer/urlCompression" -Name "doDynamicCompression" -Value true -PSPath 'IIS:\Sites\Default Web Site'
        # Set custom logging fields for IIS
        Set-WebConfigurationProperty -Filter "/system.webServer/httpLogging" -Name "dontLog" -Value false -PSPath 'IIS:\Sites\Default Web Site'
        Set-WebConfigurationProperty -Filter "/system.webServer/httpLogging" -Name "selectiveLogging" -Value "LogAll" -PSPath 'IIS:\Sites\Default Web Site'
      args:
        executable: powershell.exe

This playbook does two things:

  • It uses Ansible's win_feature module to install the IIS role and the necessary features on the Windows servers, which is a straightforward use of Ansible's built-in capabilities.
  • It then runs a PowerShell script with Ansible's win_shell module to perform more complex configurations on IIS, including setting a default document for the web server, enabling dynamic content compression to increase website performance, and configuring custom logging fields for better auditing and analytics.

Finally, you would run the main playbook:

ansible-playbook main.yml

By combining Ansible and PowerShell in this way, you can automate and handle complex server configuration tasks that go beyond the basic capabilities of Ansible's built-in modules. This method helps maintain consistency across servers, reduces manual work, and helps in troubleshooting by providing detailed logs.

Conclusion

The hybrid automation approach with PowerShell and Ansible addresses the challenges faced by system administrators in managing diverse environments. By leveraging the power of both PowerShell and Ansible, you can streamline the configuration, orchestration, and management of multiplatform environments, leading to increased operational efficiency and consistency. This powerful integration marks a significant stride in the evolution of system administration, promising an efficient, unified, and comprehensive automation platform.

The Author

Marcin Gastol is a Senior DevOps Engineer and Microsoft Certified Trainer with extensive experience in Azure technologies and teaching various IT subjects. His blog (https://marcingastol.com/) encompasses multiple IT topics.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy ADMIN Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

comments powered by Disqus