Learn Ansible
上QQ阅读APP看书,第一时间看更新

Copying an HTML file

The final task is to copy an index.html file to our web root, so we have something to serve with our newly installed Apache server. The task to do this uses the template module:

- name: copy the test HTML page to the document root
template:
src: "index.html.j2"
dest: "{{ document_root }}/index.html"
mode: "0644"
owner: "{{ users.0.name }}"
group: "{{ apache_group }}"
when: html_deploy == true

As you can see, we are loading a template called index.html.j2, which contains the following content:

<!--{{ ansible_managed }}-->
<!doctype html>
<title>{{ html_heading }}</title>
<style>
body { text-align: center; padding: 150px; }
h1 { font-size: 50px; }
body { font: 20px Helvetica, sans-serif; color: #333; }
article { display: block; text-align: left; width: 650px;
margin: 0 auto; }
</style>
<article>
<h1>{{ html_heading }}</h1>
<p>
<p>{{ html_body }}</p>
</p>
</article>

We are using two variables in our template; both of these can found in the roles/apache/defaults/main.yml file along with the variable:

html_deploy: true
html_heading: "Success !!!"
html_body: |
This HTML page has been deployed using Ansible to
<b>{{ ansible_nodename }}</b>.<br>
The user is <b>{{ users.0.name }}</b> who is in the
<b>{{ apache_group }}</b> group.<br>
The weboot is <b>{{ document_root }}</b>, the default index file is
<b>{{ index_file }}</b>.<br>

As part of the task, we have the following line:

when: html_deploy == true

This means that the task will only be executed if html_deploy equals true. If it is anything else, then the task will be skipped. We will be looking at this later in the chapter, but for now, we want the page to be deployed, so we will keep the default value defined in the apache/defaults/main.yml file.

The final thing to point out before we run the role is the html_body variable. As you can see the content of the variable is spread over three lines. This is done using the | character after the variable name; this helps make your variable files readable and also allows you to start distributing items such as keys or certificates as variables, while also allowing you to encode them using vault.