Linux Labs

Automation: Git and Ansible / Stage 5 of 6

A playbook: tasks, handlers, templates

Not running Starting usually ~20 s
Leave the lesson

Step 4 of 6 · on a machine · 7 min

A template and a trial run

A config differs from machine to machine by a couple of values. Those go into variables, and the file is built from a template.

The template module works like copy, but takes a template file with the .j2 extension and fills in variables: {{ shop_name }} is replaced with the value (in the Wiki). Play variables are set in the vars section; the -e name=value option on the command line sets a value over vars. If the templates/index.html.j2 template has the line <h1>{{ shop_name }}</h1>, this play puts a “Corner shop” page on the machine:

yaml
  vars:
    shop_name: Corner shop
  tasks:
    - name: Page
      template:
        src: templates/index.html.j2
        dest: /srv/shop/index.html

What a run would change is checked before it: ansible-playbook site.yml --check --diff. --check is a dry run: modules compare but change nothing, and the report shows what would have changed. --diff prints the file differences: a line with - is how it is now, with + how it will be. shell and command tasks do not run under --check and land in skipped: Ansible cannot tell what they would do (in the Wiki).

Exercise · do it

Move the port into a variable

The site port has to come from the play variable shop_port. In ~/ansible-lab build the nginx config from the template templates/shop.conf.j2 with this variable and set the port to 8082. Before the run, see what it would change without changing the machine. After the run the site answers on http://127.0.0.1:8082/, and the next run changes nothing.

Sign in and start The machine is available after signing in

Goals · 0 of 2

  • Build the config from a template with a port variable not done yet
  • Move the site to port 8082 so that the next run changes nothing not done yet

Step goals

0 of 2
  • Build the config from a template with a port variable — not done yet
  • Move the site to port 8082 so that the next run changes nothing — not done yet
Ubuntu 24.04

Step goals

0 of 2
  • Build the config from a template with a port variable — not done yet
  • Move the site to port 8082 so that the next run changes nothing — not done yet
Loading…