Basic File Copy Using the Copy Module
At first, you might use Ansible’s copy module to transfer a static index.html file to each web server. For example, your inventory file and playbook could be configured as follows:Introducing Variables into the Web Page
Suppose the requirement changes and you now need to display the hostname and IP address dynamically on each web server. One solution might involve creating separate versions of the index.html file for each server. For example:Converting an HTML File into a Jinja2 Template
By creating one consolidated template file with a variable placeholder, you can avoid managing multiple static files. Rename your file to indicate its templated nature, for example, index.html-template or, even better, index.html.j2. Insert a Jinja2 variable for the server name:Using the Template Module
The template module is designed to process Jinja2 templates. It replaces the variables with real values and then copies the resulting file to the target server. Update your playbook as follows and use the built-in Ansible variable to automatically insert the current host’s name:What Happens During Execution
When executing the playbook, Ansible spawns a separate process for each host. This process gathers facts—such as inventory_hostname and other host-specific information—and then executes the tasks. The template module generates a personalized index.html file with the correct hostname, and subsequently copies the file to the designated directory (/var/www/nginx-default/index.html). For example, after processing, the rendered file for web1 might appear as:Applying the Template Approach to Other Configuration Files
The templating techniques showcased for the web page can be applied to various other configuration files like nginx or Redis configurations. For instance, an nginx configuration file with variable placeholders might look like this:/etc/resolv.conf file using a loop: