Connect to the Environment

Ansible is an agentless configuration management tool. Instead of relying on an installed agent, it uses remote management protocols to communicate with remote hosts.

Ansible uses SSH to connect to Linux hosts and network devices, and WinRM to connect to Windows.

Host connection options

The following are options available to connect to Linux and Windows hosts:

Linux

  1. SSH keys over SSH(22)
  2. Username & password over SSH (22)

Windows

  1. WinRM over HTTPS (5986)
  2. WinRM over HTTP (5985)

Windows authentication options

You can authenticate with Windows hosts using the following methods:

Option Local Accounts Active Directory Accounts Credential Delegation HTTP Encryption
Basic Yes No No No
Certificate Yes No No No
Kerberos No Yes Yes Yes
NTLM Yes Yes No Yes
CredSSP Yes Yes Yes Yes

The table is taken from docs.ansible.com.

How you set up the remote management is dependent on the environment.

Connect to a Windows Host

Ansible uses PowerShell remoting over WinRM to connect to Windows hosts. Ansible will attempt to connect to a Windows host using WinRM over HTTPS on port 5986. Windows Server does not have PowerShell remoting via HTTPS preconfigured.

We think it best to use Ansible for all the configurations. Having to configure something before you can use Ansible is a chicken and egg scenario. You can deal with this problem in one of three ways:

  1. Bootstrap the WinRM configuration;
    • AWS and Azure provide features that allow you to run scripts at startup.
  2. Embed the changes into an image;
    • Build a custom image that has WinRM configured.
  3. Use WinRM over HTTP on port 5985;
    • Windows Server 2012r2 and later have PowerShell remoting configured on port 5985.

We solved this problem by executing the Ansible playbooks Create Windows Virtual Machine in Azure and AWS. Each of the playbooks contained a configuration for bootstrapping the WinRM configuration with a PowerShell script, ConfigureRemotingForAnsible.ps1.

The script generates self-signed certificates for using HTTPS and modifies the firewall rules to allow HTTPS traffic on port 5896.

Let’s review the sections for bootstrapping in both AWS and Azure playbooks.

Azure

The azure_create_windows_vm.yaml playbook uses a CustomScriptExtension to download and execute the PowerShell script, ConfigureRemotingForAnsible.ps1. Review Line 7 and 9 in the playbook below:

Press + to interact
- name: Windows - create Azure vm extension to enable HTTPS WinRM listener
azure_rm_virtualmachineextension:
name: winrm-extension
resource_group: ansible
virtual_machine_name: "vm-winweb{{ count }}"
publisher: Microsoft.Compute
virtual_machine_extension_type: CustomScriptExtension
type_handler_version: '1.10'
settings: '{"fileUris": ["https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1"],"commandToExecute": "powershell -ExecutionPolicy Unrestricted -File ConfigureRemotingForAnsible.ps1"}'
auto_upgrade_minor_version: true

AWS

Review the playbook below:

Press + to interact
- name: windows - create ec2 instance
ec2:
key_name: aws-ansible-key
instance_type: t2.micro
image: ami-0ac51e8ec52326463
region: us-east-1
group: windows
count: 1
vpc_subnet_id: "{{ ansible_subnet.subnets[0].id }}"
user_data: |
<powershell>
$content = (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1' -UseBasicParsing).content
iex $content
$password = "{{ password }}" | ConvertTo-SecureString -AsPlainText -Force
New-LocalUser 'ansible' -Password $password
Add-LocalGroupMember -Group 'Administrators' -Member 'ansible'
</powershell>
<persist>true</persist>
wait: yes
assign_public_ip: yes
instance_tags:
Name: winweb01
app: ansible
env: dev
os: windows
register: ec2

Here is the breakdown of the highlighted lines:

  • Line-10: With AWS instance user data, you can run configuration scripts during the launch.
  • Line-12: Get contents of ConfigureRemotingForAnsible.ps1.
  • Line-13: Run ConfigureRemotingForAnsible.ps1.
  • Line-14: Create an Ansible user & add to the local Administrators group.

Within the aws_create_windows_ec2_instance.yaml playbook, user data is used to run a PowerShell cmdlet to store the contents of ConfigureRemotingForAnsible.ps1 in a variable. It then uses Invoke-Expression to execute the script.

Test Windows Host Connectivity

Use the win_ping.yaml playbook to test the Windows virtual machine’s connectivity. Review the playbook below:

---
- hosts: all
  gather_facts: false

  vars_prompt:
    - name: password
      prompt: "Enter ansible user password"

  vars:
    ansible_user: ansible
    ansible_password: "{{ password }}"
    ansible_connection: winrm
    ansible_winrm_transport: ntlm
    ansible_winrm_server_cert_validation: ignore

  tasks:
  - name: run win_ping
    win_ping:
win_ping.yaml

Ansible communicates with the Windows host over WinRM using NTLM authentication. For this course, you will use the self-signed certificates; that’s why the certificate validation is turned off. The playbook contains a single task that uses the win_ping Ansible module to test the connectivity to remote Windows hosts.

Click on the Run button, and wait for the environment to set up. Once run, you can execute the playbook by running the following command in the terminal of the widget above:

Press + to interact
# Replace the <Public Ip Address> with the IP of Azure virtual machine
# or AWS EC2 instance for Windows
ansible-playbook win_ping.yaml -i <Public Ip Address>,

Replace the <Public Ip Address> with the Public IP address associated with the Azure virtual machine or AWS EC2 instance. When you run the command, a prompt for the password will be displayed; use the same password as in the previous lessons.

The , at the end of the IP address bypasses the Ansible inventory parser. This allows you to pass a list of hostnames or IP addresses instead of an inventory file.

The output will look like the one below in case of failure or success:

PLAY [all]
*********************************************************************************************
TASK [run win_ping]
************************************************************************************
ok: [Public IP Address]
PLAY RECAP *********************************************************************************************
Public IP Address : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Success

Test Linux Host Connectivity

Use the ping.yaml playbook to test the Linux virtual machine’s connectivity. Review the playbook below:

---
- hosts: all
  gather_facts: false

  vars_prompt:
    - name: password
      prompt: "Enter ansible user password"

  vars:
    ansible_user: ansible
    ansible_password: "{{ password }}"
    ansible_ssh_common_args: '-o StrictHostKeyChecking=no'

  tasks:
  - name: run ping
    ping:
ping.yaml

The playbook defines a few variables that configure the SSH username and password. Line-12 disables host key checking. It contains a single task that uses the ping Ansible module to test the remote Linux host’s connectivity.

Click on the Run button, and wait for the environment to set up. Once run, you can execute the playbook by running the following command in the terminal of the widget above:

Press + to interact
# Replace the <Public Ip Address> with the IP of Azure virtual machine
# or AWS EC2 instance for Windows
ansible-playbook ping.yaml -i <Public Ip Address>,

Replace the <Public Ip Address> with the Public IP address associated with the Azure virtual machine or AWS EC2 instance. When you run the command, a prompt for the password will be displayed; use the same password as in the previous lessons.

Troubleshooting tips

Missing module winrm
FAILED! winrm or requests is not installed: No module named winrm.

After running the win_ping.yaml playbook, you will encounter the error winrm or requests is not installed. The Python module that supports WinRM connections is not installed by default.

In that case, you can use pip3 to install the missing module pywinrm.

Press + to interact
pip3 install "pywinrm>=0.3.0"

Missing program sshpass
FAILED! to use the 'ssh' connection type with passwords, you must install the sshpass program.

Ansible has two methods for connecting to a Linux host:

  1. SSH keys
  2. Username and password

By default, Ansible will opt for ssh keys. You can choose to use a username and password by defining the variable ansible_password. This requires the sshpass package to be installed. You can do that by executing the following command:

Press + to interact
apt install -y sshpass

In this lesson, we looked at the following tools and options to connect to Linux and Windows virtual machines:

  1. WinRM to connect to Windows.
  2. SSH to connect to Linux hosts.
  3. Bootstrapping the WinRM configuration with a PowerShell script. ConfigureRemotingForAnsible.ps1 for Windows’ hosts.

You learned how to install the following two programs in your environment:

  • sshpass for Linux
  • winrm for Windows

Get hands-on with 1300+ tech skills courses.