Send emails through ansible

Recently I was watching this video and got to know about `mail` attribute in ansible and we can send emails through it and I gave it a try and finally after some hacks I sent an email from my one account to another.

Here below code I have written to send the email –

- hosts: webservers
  - name: Sending an e-mail using Gmail SMTP servers
      port: 587
      password: yourPassword
      to: Aniruddha Basak <>
      subject: Ansible check email
      body: I am using {{ ansible_facts['os_family'] }}.
    delegate_to: localhost

Above we are using gmail SMTP server. In case you are using 2FA of google then you have to add a device password for that and write the password in the password field.

Encrypt your files by Ansible Vault

So, in previous blog I have given you a brief description about ansible roles. In this blog I am going to discuss about another very important topic that is ansible vault.

Why we need encryption?

We write our ansible playbook, jinja templates and other files in normal unencrypted format but we can’t keep our crucial information such as password in unencrypted format so that’s why we need encryption.

How we can encrypt?

Just like we use ansible-playbook to run our ansible playbooks we have a option called ansible-vault to do our encryption and decryption work. Here below some important and useful commands –

  • we use ansible-vault create a_file to create a encrypted file
$ ansible-vault create a_file
New Vault password: 
Confirm New Vault password:
  • we use ansible-vault encrypt a_existing_file to encrypt a existing file
$ ansible-vault encrypt a_existing_file 
New Vault password: 
Confirm New Vault password: 
Encryption successful
  • we use ansible-vault view a_file to view the encrypted file
$ ansible-vault view a_file 
Vault password: 
You are reading Aniruddha's Blog ;)
  • we use ansible-vault decrypt a_file to decrypt any encrypted file
$ ansible-vault decrypt a_file 
Vault password: 
Decryption successful

What is vault ID?

A vault ID is an identifier for one or more vault secrets. Vault IDs, you must provide an ID of your choosing and a source to obtain it’s password (either prompt or a file path). We use --vault-id to provide the ID. Here below examples how we do –

  • We encrypt a file with ID
$ ansible-vault encrypt --vault-id id1@prompt a_file 
New vault password (id1): 
Confirm vew vault password (id1): 
Encryption successful
  • we view a file with ID
$ ansible-vault view --vault-id id1@prompt a_file 
Vault password (id1): 
You are reading Aniruddha's Blog ;)
  • we decrypt a file with ID
$ ansible-vault decrypt --vault-id id1@prompt a_file 
Vault password (id1): 
Decryption successful

Thank you 🙂