Skip to main content

How to work with Ansible templates

Ansible is a very powerful language that can be used in infrastructure as code, or the idea of using playbooks that can deploy IT environments in a reproducible manner. One of the powerful features that Ansible provides is the concept of templates. Here, we’ll go over a simple example of how to deploy a MailEnable installation with a domain name, catch-all mailbox and other configuration options.

First, we’ll need a short PowerShell script which will configure the MailEnable instance. Save this file as templates/install_mailenable.ps1.

$ErrorActionPreference = 'stop'
Add-PSSnapin MailEnable.Provision.Command
try
{
    New-MailEnablePostOffice -Postoffice '' -Domain ''
}
catch
{
    if (-Not ($_.Exception.Message -Like '*because they already existed'))
    {
        throw
    }
}
$mailbox_map = Get-MailEnableAddressMap -Postoffice '' -Mailbox postmaster | Where-Object { $_.SourceAddress -eq '[SMTP:*@]' }
if ($mailbox_map -eq $null)
{
    New-MailEnableAddressMap -Postoffice '' -Mailbox postmaster -EMailAddress '[SMTP:*@]'
}
Set-MailEnableMailbox -Postoffice '' -Mailbox postmaster -Setting mailboxPassword -Value ''

One thing you may notice is a number of variables, like mail_domain and mail_password. This allows us to have a single template file, and re-use it for multiple deployments by defining those values in the playbook.

Now that we have our template, here is the playbook where we can use it:

---
- hosts: all
  vars:
  - mail_domain: "example.com"
    mail_password: "12345"
  tasks:
  - name: Fetching Mail Enable
    win_get_url:
      url: https://www.mailenable.com/standard1023.exe
      dest: C:\Windows\Temp\mailenable.exe
  - name: Installing Mail Enable
    win_shell: C:\Windows\Temp\mailenable.exe /s
  - name: Crafting configuration script
    win_template:
     src: install_mailenable.ps1
     dest: C:\Windows\Temp\mailenable.ps1
  - name: Configuring Mail Enable
    win_shell: C:\Windows\Temp\mailenable.ps1
  - name: Cleaning up
    win_file:
      path: C:\Windows\Temp\mailenable.exe
      state: absent

You can save this as mailenable.yml among your other playbooks. The first thing to notice in this file is that we define the two variables that are used by the template. Then, we download Mail Enable using win_get_url and install it. Then we upload the PowerShell template using win_template. Note that while this is a PowerShell template on a Windows host, but you can use a Bash script on a Linux host, and then the task to use would be template.