If you’ve ever wanted to add a comment block to a file with Ansible it is pretty easy. Just add the “comment” filter to the text you want to use as a comment. But what if you want to have an inline comment?
For example, in a Linux config file like /etc/hosts you can have Ansible add a comment block:
#
# This is for my NAS
#
192.168.1.100 nas
But, what if you want to have the comment at the end of the line (an inline comment)?
192.168.1.100 nas # This is for my NAS
Ansible Comment
Adding a comment with Ansible is easy.
And when adding a comment in a Linux config file, you need to use the # character.
This can be accomplished using Ansible’s “comment filter“.
ansible_variable1: "192.168.1.100 nas {{ 'This is for my NAS' | comment }}"
The result will be:
TASK [Print normal comment] ********************************************************************************************
ok: [localhost] => {
"msg": "#\n# This is for my NAS\n#\n192.168.1.100 nas"
}
And when using something like the Ansible Module lineinfile, you would get:
#
# This is for my NAS
#
192.168.1.100 nas
Ansible Inline Comment
Adding an inline comment with Ansible isn’t obvious. You can’t just add the # character as part of the text in the Ansible yaml. Because that’s actually a comment in the yaml file.
You need to use Ansible’s “comment filter“, like a normal comment, however you need to change a few options.
Modify the prefix and postfix options for the comment filter:
ansible_variable2: "192.168.1.100 nas {{ 'This is for my NAS' | comment('plain', prefix='', postfix='') }}"
The result will be:
TASK [Print inline comment] ********************************************************************************************
ok: [localhost] => {
"msg": "192.168.1.100 nas # This is for my NAS\n"
}
And when using something like the Ansible Module lineinfile, you would get:
192.168.1.100 nas # This is for my NAS
Demo
Here is a demo Ansible Playbook to test with.
---
- hosts: localhost
name: Ansible Inline Comment Demo
vars:
my_other_var: "nas"
ansible_variable1: "{{ 'This is for my NAS' | comment }}\n192.168.1.100 {{ my_other_var }}"
ansible_variable2: "192.168.1.100 {{ my_other_var }} {{ 'This is for my NAS' | comment('plain', prefix='', postfix='') }}"
tasks:
- name: Print normal comment
debug:
msg: "{{ ansible_variable1 }}"
- name: Print inline comment
debug:
msg: "{{ ansible_variable2 }}"
If you want to get started with Ansible, check out my post: Getting Started with Ansible. It has some Ansible basics that can help you get started.