Day-23: Automating Nginx & MySQL Setup with Ansible Jinja2 Templates
Ansible Jinja2 Templates:
Ansible Jinja2 is a tool used in Ansible to help create dynamic configuration files and scripts. Instead of manually editing files, you can use placeholders in your templates, which are then replaced with actual values when the playbook runs.
With Jinja2 templates, you can create flexible configurations that work across different servers and environments, all from one template. It’s a real time-saver and ensures everything is set up consistently across multiple systems.
Basically, it automates the process of filling in the right information where it’s needed, which makes repetitive tasks much easier and faster.
. Now, log in to the AWS EC2 console with root access. Once logged in, navigate to the Ansible directory at /etc/ansible/
. In this directory, remove the old ansible.cfg
file. After that, create a new ansible.cfg
file as needed.
cp ansible.cfg /tmp/ or
rm -rf ansible.cfg
. Next, we can create a new Ansible configuration file in the /etc/ansible/
directory using the command below.
ansible-config init --disabled > ansible.cfg
. Now we can edit the ansible.cfg file like this host_key_checking=False and remote_user=ansibleadmin , private_key_file=/home/ansibleadmin/key.pem .
. Now we can clone the client's git repo into ansible-files location then enter the below commands to create clients' servers with terraform.
cd ansible-files
git clone https://github.com/mokadi-suryaprasad/Ansible-day-01.git
terraform init
terraform apply --var-file "15.terraform.tfvars"
ansible -i invfile all -m ping
. Now, we can run the Jinja2 template and observe how it works on the server.
ansible-playbook -i invfile playbooks01/5.Jinja/nginx-jinja2.yml --syntax-check
ansible-playbook -i invfile playbooks01/5.Jinja/nginx-jinja2.yml --syntax-check
ansible-playbook -i invfile playbooks01/5.Jinja/nginx-jinja2.yml --check
ansible-playbook -i invfile playbooks01/5.Jinja/nginx-jinja2.yml -vv
. Now, we can confirm that we have successfully deployed our Jinja2 template on the client servers.
Deploying MySQL Jinja2 templates in client servers.
. Now, we can check whether MySQL is installed on our client servers.
ansible -i invfile pvt -m shell -a "service mysql status"
sudo apt update
apt install -y python3-pip
ansible-playbook -i invfile playbooks01/5.Jinja/mysql-jinja2.yml
ansible -i invfile pvt -m shell -a "service mysql status"
. Now, we can log in to the client public-server01
and check if MySQL is installed. We can also run queries to inspect the data inside the tables.
service mysql status
mysql
SHOW DATABASES;
use myflixdb;
show tables;
select * from movies;
. Now, we can run the pre
and post
tasks from the tasks.yml
files in the ansible-files
directory and back up the files to a remote location.
ansible-playbook -i invfile playbooks01/5.Jinja/pre_post_tasks.yml
Thanks for reading my blogs.