Templates

In previous playbooks we've seen templates and filters.

They are applied via the template module.


In [ ]:
cd /notebooks/exercise-07

Let's review one of the previous templates used via the lineinfile module:

<html>
   <body>
       System installed by {{ansible_hostname}} on {{ '{{' }} ansible_hostname {{ '}}' }}
   </body>
</html>

This maps to

<html>
   <body>
       System installed by foo.example.com on {{ ansible_hostname }}
   </body>
</html>

Another way of using templates is to enforcing policies, like:

  • logging centralization, naming and rotating
  • limits enforcement
  • whatever

Log rotation

#
# Rotate {{programname}} logs generated by rsyslog_simple.j2 .
#
{{ "/".join(("/var/log/", dirname, "*.log")).replace("//", "/") }}  {
        missingok
        compress
        copytruncate
        daily
        rotate 31
        minsize 2048
        notifempty
}

Logfile naming

#
# Log {{programname}} in its file.
#
#  {{programname}} includes port and pid in {{programname}},
#  so we use startswith.
#
# Logs from emerg to notice go to {{programname}}.log
if $programname startswith '{{programname}}'  and $syslogseverity <= 5 then /var/log/{{dirname}}{{programname}}.log


# Logs for info to debug to {{programname}}-debug.log 

if $programname startswith '{{programname}}'  and $syslogseverity > 5 then /var/log/{{dirname}}{{programname}}-debug.log                                                                                                           

# Don't spam with this logs other files but the ones above (eg. don't log to messages)                             
if $programname startswith '{{programname}}'  then ~

Lookups

Lookup plugins allow ansible control machine to access local or external sources.

This includes:

  • files, csv, ...
  • databases (mongo, dns, redis, ..)
  • command pipe, environment variables

Here is a simple lookup playbook

- hosts: localhost
  tasks:
  - name: Here is a simple lookup
    debug:
      msg: >
        lookup('file', '/etc/resolv.conf')

In [ ]:
!ansible-playbook -v lookup.yml

Exercise

Exercise

In this recap exercise, write the add_key.yml playbook which:

  • authenticates with root:root credentials on remote hosts
  • generate a new ecdsa PK for local root
  • creates the fizz user on remote hosts with:
    • a keypair
    • a password
  • retrieves the generated ecdsa PK with lookups
  • add the PK to the remote authorized_keys

Learn how to use add_host to add hosts to the inventory.

  • tests

In [ ]:
# Use this cell for the exercise
!ansible-playbook add_key.yml

In [ ]: