Configure Ansible to Use Inventories And Variables

In this blog post, we will take a deep dive into Ansible’s advanced configuration and how to use inventories and variables.

During my blog series about how to Manage Windows Machines with Ansible, we used the default inventory file to add our hosts and however this is not ideal or recommended according to the  Ansible’s best practices.

Best Practices

Ansible’s best practices recommend that we create the following:

  • Inventory file for our hosts
  • Place variables in a variable file under the directory (need to create) group_vars.
  • use playbooks.

Following the above, I will do the following:

  • Create an inventory file called addcservers with my Domain Controllers servers
  • Create a group_vars directory under /etc/ansible
  • Create a variables file called addcservers under groups_vars.
  • Create a simple playbook

Let’s get to work.

Create Group_Vars Directory

To create the group_vars directory I will use the following command which will create it.

mkdir group_vars

Note: make sure you create the directory under /etc/ansible

Below you can see the content of my group_vars file:

ansible_user: ansible
ansible_password: passwords
ansible_connection: winrm
ansible_winrm_transport: ntlm
ansible_winrm_server_cert_validation: ignore

The file contains all the variables we used in the hosts’ file.

Create Inventory

Let’s go ahead and create our inventory file which by copying the hosts file to a new file and removing all the content.

cp hosts addcservers

Note: this file doesn’t need to be located in /etc/ansible however it needs to have the same name as variables file under group_vars.

Below is the content of my inventory file.

[addcservers]
192.168.0.50
192.168.0.51

Create a Playbook

In the last step of the configuration, I will create a playbook for my Domain Controllers.

---
- name: "Run PoweShell cmdlets"
  hosts: addcservers
  tasks:
       - win_shell: Install-PackageProvider -Name NuGet -force

Run Playbook

The final step is to run the playbook using the command below, which will use the inventory switch -i to use the addcservers file and Ansible will find the variables file automatically.

ansible-playbook -i addcservers install_nuget.yaml

Processing…
Success! You're on the list.

Posted

in

by