SlideShare a Scribd company logo
MariaDB, MySQL and Ansible:
automating database infrastructures
Federico Razzoli
$ whoami
Hi, I’m Federico Razzoli from Vettabase Ltd
Database consultant, open source supporter,
long time MariaDB and MySQL user
● vettabase.com
● Federico-Razzoli.com
This talk
● General Ansible concepts
● Opinionated code examples, automating MariaDB/MySQL
● Good and bad practices
Ansible Overview
What is Ansible
● A tool for deployment and configuration automation
● Infrastructure as code
● Idempotent
● Simple, non-centralised
Ansible Concepts
● Inventory
● Module
● Playbook
● Role
● Play
● Variable
● Facts
Inventories
Inventory example
[pmm]
pmm-1
[mariadb_main]
mariadb-main-1
mariadb-main-2
mariadb-main-3
[mariadb_main:vars]
pmm_server_host=pmm-1
pmm_server_port=80
Ansible hosts
[pmm]
pmm-1 ansible_host=123.123.123.123
[mariadb_main]
mariadb-main-1 ansible_host=123.0.0.1
mariadb-main-2 ansible_host=123.0.0.2
mariadb-main-3 ansible_host=123.0.0.3
[mariadb_main:vars]
pmm_server_host=123.123.123.123
pmm_server_port=80
● Sometimes we cannot use meaningful hostnames
Hierarchical groups
[mariadb_master]
mariadb-master-1
mariadb-master-2
[mariadb_replica]
mariadb-replica-1
mariadb-replica-2
[mariadb:children]
mariadb_master
mariadb_replica
● We have different groups for masters and replicas, and a supergroup that
includes them both
Groups goals
● You assign each group some roles
● You can deploy one or more group
Multiple inventories
production_db:
[mariadb_master]
mariadb-master-1 ansible_host=111.0.0.1
mariadb-master-2 ansible_host=111.0.0.2
staging_db:
[mariadb_master]
mariadb-master-1 ansible_host=222.0.0.1
mariadb-master-2 ansible_host=222.0.0.2
Plays
Play example
---
- hosts: mariadb_main
roles:
- linux-for-mysql
- mariadb
- hosts: mysql_main
roles:
- linux-for-mysql
- mysql
● You assign roles to groups (or individual hosts)
Applying all roles to a certain host
Call Ansible specifying an inventory and a play:
% ansible-playbook -i staging -l mariadb_main main.yml
Play example
Here is where it can be convenient to have multiple inventories:
% ansible-playbook -i staging -l mariadb_main main.yml
% ansible-playbook -i production -l mariadb_main main.yml
Roles, variables and templates
Example
- name: Create script dir
file:
name: "{{ script_dir }}"
owner: root
group: root
mode: 755
state: directory
● This is a task, but the term is misleading
● A role is a list of tasks
● The name appears on screen
● "file" is the module
● script_dir is a variable
Defining variables
script_dir: /opt/scripts
base_dir: /usr/local/mysql
...
● /host_vars/<host_name>.yml
● /group_vars/<group_name>.yml
● /roles/<role_name>/defaults/main.yml
Notes on variables
● The same variable can be used by multiple roles
● Roles from Ansible Galaxy can’t use this opportunity
● This is a good reason to make your own roles
● Document what each variable does in README.md
Copying a configuration file
- name: Copy my.cnf
copy:
src: ./files/my.cnf
dest: "/etc/mysql/{{ inventory_hostname }}.cnf"
● my.cnf is copied to /etc/mysql
Using a template
- name: Copy my.cnf
template:
src: ./templates/my.cnf .j2
dest: /etc/mysql/my.cnf
● This time my.cnf is a Jinja 2 template
Template example
[mysqld]
user = mysql
datadir = {{ mysql_data_dir }}
innodb_buffer_pool_size = {{ innodb_buffer_pool_size }}
● This time my.cnf is a Jinja 2 template
Problems
● If we want to set a variable, we should be able to add it in one place
○ host_vars or group_vars or role's defaults
● We can make a template more dynamic
Dynamic template example
In group_vars we create a list of dictionaries:
(arrays of objects, if you prefer)
group_mysql_variables:
- { name: 'innodb_buffer_pool_size', value: '50G' }
- { name: 'innodb_log_file_size', value: '50G' }
In host_vars we optionally create another list:
host_mysql_variables:
- { name: 'innodb_buffer_pool_size', value: '80G' }
Dynamic template example
We loop over both the lists in the template:
{% for var in group_mysql_variables %}
{{ var.name }} = {{ var.value }}
{% endfor %}
{% if host_mysql_variables is defined %}
{% for var in host_mysql_variables %}
{{ var.name }} = {{ var.value }}
{% endfor %}
{% endif %}
Notes
● We cannot use the same list in group_vars and host_vars, because the
one in host_vars would overwrite the whole list
● Some variables may appear twice in the configuration file
● This is fine: the last occurrence of a variable will override the previous one
Another use for lists
Hosts of a cluster can be a list too:
# print the IPs separated by commas
wsrep_cluster_address = gcomm://{{ private_ips|join(',') }}
# first node is the donor
wsrep_sst_donor = {{ cluster_hosts[0].node_name }}
# Only the first node imports a backup when the cluster is created
- name: Import backup
...
when: cluster_hosts[0] == hostvars[inventory_hostname]['ansible_default_ipv4']['address']
Validate variables
Validate variables for complex roles:
- name: Validate cluster size
assert:
that: cluster_hosts|length > 0
fail_msg: cluster_hosts must contain at least 1 element
success_msg: "cluster_hosts size: {{ cluster_hosts|length }}"
- name: Validate cluster IPs
assert:
that: "'{{ item.public_ip }}'|ipaddr"
fail_msg: "{{ item.public_ip }} is not a valid IP"
success_msg: "{{ item.public_ip }}: OK"
with_items: "{{ cluster_hosts }}"
Tags and similar features
Conditional tasks
● Certain tasks should only be run for certain servers:
- name: Make server read only
mysql_variables:
variable: read_only
value: 1
when:
is_replica is sameas true
● Sometimes this avoids the need to create multiple roles which are very similar
● Instead of creating mariadb and mariadb_replica roles, we may create
mariadb only, with some conditional tasks
○ Sometimes it makes sense, sometimes it doesn't
Conditional tasks
● We can group optional tasks into separate files:
- name: Make server read only
include: replica.yml
when:
is_replica is sameas true
Idempotency of Tasks
● Most modules are idempotent
● This means that you can run a task like this multiple times safely:
- name: Start MariaDB
service:
state: started
● If the service is already running, nothing happens
Idempotency of Tasks
● Sometimes you make non-idempotent tasks on purpose:
- Copy my.cnf
...
- name: Restart MariaDB
service:
state: restarted
● If the service is already running, nothing happens
Idempotency of Tasks
● Sometimes you'd like a task to be idempotent, but it can't be:
- name: Run a system command
shell: >
rm "{{ mysql_data_dir }}"/*
- name: Run a script
shell: >
"{{ mysql_script_dir }}"/my_script.py
- name: Run some SQL
mysql_query:
query: CREATE OR REPLACE TABLE db.table ( ... );
● Ansible doesn't understand system commands, scripts or queries, so it has not
way to check if they were already run. It runs them every time.
Tags
● Ansible supports tags
● Each task can be assigned a list of tags:
- name: (Re)create users
...
- name: Update timezone info
tags: [ tzinfo-update ]
...
- name: Do something else
...
ansible-playbook -i production_mysql --tag tzinfo-update production.yml
Tags
● Typical tasks I want to have:
- name: Do something
- name: Copy my.cnf
tags: [ mysql-config- static-update ]
- name: Restart MySQL
tags: [ mysql-config- static-update ]
- name: Set variables at runtime
tags: [ mysql-config- dynamic-update ]
- name: Do something else
Tags
● So there is a way to selectively run certain tasks
● But what if we want to selectively exclude certain tasks?
● There is not built-in way, but we can do something like this:
- name: Do something
- name: Restart MySQL
service:
state: restarted
when: {{ mysql_restart }} is defined and {{ mysql_restart }} is sameas true
- name: Do something else mething else
ansible-playbook -i production_mysql 
--tag mysql-config-dynamic-update -e 'mysql_no_restart=1' production.yml
Thanks for attending!
Question time :-)
xxxxx
● Xx
● yy
Example
CREATE OR REPLACE TABLE ticket (
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
state ENUM('OPEN', 'VERIFIED', 'FIXED', 'INVALID') NOT NULL
DEFAULT 'OPEN',
summary VARCHAR(200) NOT NULL,
description TEXT NOT NULL
)
ENGINE InnoDB
;
● We want to start to track changes to bugs over time

More Related Content

What's hot (20)

PPTX
Maxscale 소개 1.1.1
NeoClova
 
PDF
Introduction to MongoDB
Mike Dirolf
 
PDF
Memory Management with Page Folios
Adrian Huang
 
PPTX
Running MariaDB in multiple data centers
MariaDB plc
 
PDF
Ceph Object Storage Reference Architecture Performance and Sizing Guide
Karan Singh
 
PDF
Load Balancing MySQL with HAProxy - Slides
Severalnines
 
PPTX
Deploying MariaDB databases with containers at Nokia Networks
MariaDB plc
 
PDF
LISA2019 Linux Systems Performance
Brendan Gregg
 
PPTX
Automating with Ansible
Ricardo Schmidt
 
PDF
How to Manage Scale-Out Environments with MariaDB MaxScale
MariaDB plc
 
PDF
IT Automation with Ansible
Rayed Alrashed
 
PDF
Memory Mapping Implementation (mmap) in Linux Kernel
Adrian Huang
 
ODP
OpenGurukul : Database : PostgreSQL
Open Gurukul
 
PPTX
NGINX: Basics and Best Practices
NGINX, Inc.
 
PDF
Using eBPF for High-Performance Networking in Cilium
ScyllaDB
 
PDF
Using all of the high availability options in MariaDB
MariaDB plc
 
PDF
Kubernetes - introduction
Sparkbit
 
PDF
Ansible, MongoDB Ops Manager and AWS v1.1
Michael Lynn
 
PDF
Ansible Introduction
Robert Reiz
 
PDF
Maxscale switchover, failover, and auto rejoin
Wagner Bianchi
 
Maxscale 소개 1.1.1
NeoClova
 
Introduction to MongoDB
Mike Dirolf
 
Memory Management with Page Folios
Adrian Huang
 
Running MariaDB in multiple data centers
MariaDB plc
 
Ceph Object Storage Reference Architecture Performance and Sizing Guide
Karan Singh
 
Load Balancing MySQL with HAProxy - Slides
Severalnines
 
Deploying MariaDB databases with containers at Nokia Networks
MariaDB plc
 
LISA2019 Linux Systems Performance
Brendan Gregg
 
Automating with Ansible
Ricardo Schmidt
 
How to Manage Scale-Out Environments with MariaDB MaxScale
MariaDB plc
 
IT Automation with Ansible
Rayed Alrashed
 
Memory Mapping Implementation (mmap) in Linux Kernel
Adrian Huang
 
OpenGurukul : Database : PostgreSQL
Open Gurukul
 
NGINX: Basics and Best Practices
NGINX, Inc.
 
Using eBPF for High-Performance Networking in Cilium
ScyllaDB
 
Using all of the high availability options in MariaDB
MariaDB plc
 
Kubernetes - introduction
Sparkbit
 
Ansible, MongoDB Ops Manager and AWS v1.1
Michael Lynn
 
Ansible Introduction
Robert Reiz
 
Maxscale switchover, failover, and auto rejoin
Wagner Bianchi
 

Similar to MariaDB, MySQL and Ansible: automating database infrastructures (20)

PDF
Ansible is Our Wishbone
Mydbops
 
PDF
Ansible is Our Wishbone(Automate DBA Tasks With Ansible)
M Malai
 
PDF
Ansible : what's ansible & use case by REX
Saewoong Lee
 
PDF
Dal caos all’automazione di sistemi e infrastrutture IT con Ansible
Commit University
 
PPTX
Introduction to Ansible - Jan 28 - Austin MeetUp
tylerturk
 
PPTX
ansible : Infrastructure automation,idempotent and more
Sabarinath Gnanasekar
 
PDF
Managing PostgreSQL with Ansible - FOSDEM PGDay 2016
Gulcin Yildirim Jelinek
 
PDF
Managing MySQL with Ansible
Ben Mildren
 
PDF
Ansible at work
Bas Meijer
 
PPTX
Herd your chickens: Ansible for DB2 configuration management
Frederik Engelen
 
PDF
DevOps Meetup ansible
sriram_rajan
 
PDF
Script it
Giuseppe Maxia
 
PPTX
Ansible MySQL MHA
Alkin Tezuysal
 
PDF
Ansible automation tool with modules
mohamedmoharam
 
PDF
Managing Postgres with Ansible
Gulcin Yildirim Jelinek
 
PDF
Ansible to provision your machines
Fellipe Callegas
 
PDF
Ansible - Hands on Training
Mehmet Ali Aydın
 
PDF
Ansible Tutorial.pdf
NigussMehari4
 
PDF
Getting Started with Ansible - Jake.pdf
ssuserd254491
 
PDF
Introducing Ansible
Francesco Pantano
 
Ansible is Our Wishbone
Mydbops
 
Ansible is Our Wishbone(Automate DBA Tasks With Ansible)
M Malai
 
Ansible : what's ansible & use case by REX
Saewoong Lee
 
Dal caos all’automazione di sistemi e infrastrutture IT con Ansible
Commit University
 
Introduction to Ansible - Jan 28 - Austin MeetUp
tylerturk
 
ansible : Infrastructure automation,idempotent and more
Sabarinath Gnanasekar
 
Managing PostgreSQL with Ansible - FOSDEM PGDay 2016
Gulcin Yildirim Jelinek
 
Managing MySQL with Ansible
Ben Mildren
 
Ansible at work
Bas Meijer
 
Herd your chickens: Ansible for DB2 configuration management
Frederik Engelen
 
DevOps Meetup ansible
sriram_rajan
 
Script it
Giuseppe Maxia
 
Ansible MySQL MHA
Alkin Tezuysal
 
Ansible automation tool with modules
mohamedmoharam
 
Managing Postgres with Ansible
Gulcin Yildirim Jelinek
 
Ansible to provision your machines
Fellipe Callegas
 
Ansible - Hands on Training
Mehmet Ali Aydın
 
Ansible Tutorial.pdf
NigussMehari4
 
Getting Started with Ansible - Jake.pdf
ssuserd254491
 
Introducing Ansible
Francesco Pantano
 
Ad

More from Federico Razzoli (20)

PDF
MariaDB Data Protection: Backup Strategies for the Real World
Federico Razzoli
 
PDF
MariaDB/MySQL_: Developing Scalable Applications
Federico Razzoli
 
PDF
Webinar: Designing a schema for a Data Warehouse
Federico Razzoli
 
PDF
High-level architecture of a complete MariaDB deployment
Federico Razzoli
 
PDF
Webinar - Unleash AI power with MySQL and MindsDB
Federico Razzoli
 
PDF
MariaDB Security Best Practices
Federico Razzoli
 
PDF
A first look at MariaDB 11.x features and ideas on how to use them
Federico Razzoli
 
PDF
MariaDB stored procedures and why they should be improved
Federico Razzoli
 
PDF
Webinar - MariaDB Temporal Tables: a demonstration
Federico Razzoli
 
PDF
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
Federico Razzoli
 
PDF
MariaDB 10.11 key features overview for DBAs
Federico Razzoli
 
PDF
Recent MariaDB features to learn for a happy life
Federico Razzoli
 
PDF
Advanced MariaDB features that developers love.pdf
Federico Razzoli
 
PDF
Creating Vagrant development machines with MariaDB
Federico Razzoli
 
PDF
Playing with the CONNECT storage engine
Federico Razzoli
 
PDF
MariaDB Temporal Tables
Federico Razzoli
 
PDF
Database Design most common pitfalls
Federico Razzoli
 
PDF
MySQL and MariaDB Backups
Federico Razzoli
 
PDF
JSON in MySQL and MariaDB Databases
Federico Razzoli
 
PDF
How MySQL can boost (or kill) your application v2
Federico Razzoli
 
MariaDB Data Protection: Backup Strategies for the Real World
Federico Razzoli
 
MariaDB/MySQL_: Developing Scalable Applications
Federico Razzoli
 
Webinar: Designing a schema for a Data Warehouse
Federico Razzoli
 
High-level architecture of a complete MariaDB deployment
Federico Razzoli
 
Webinar - Unleash AI power with MySQL and MindsDB
Federico Razzoli
 
MariaDB Security Best Practices
Federico Razzoli
 
A first look at MariaDB 11.x features and ideas on how to use them
Federico Razzoli
 
MariaDB stored procedures and why they should be improved
Federico Razzoli
 
Webinar - MariaDB Temporal Tables: a demonstration
Federico Razzoli
 
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
Federico Razzoli
 
MariaDB 10.11 key features overview for DBAs
Federico Razzoli
 
Recent MariaDB features to learn for a happy life
Federico Razzoli
 
Advanced MariaDB features that developers love.pdf
Federico Razzoli
 
Creating Vagrant development machines with MariaDB
Federico Razzoli
 
Playing with the CONNECT storage engine
Federico Razzoli
 
MariaDB Temporal Tables
Federico Razzoli
 
Database Design most common pitfalls
Federico Razzoli
 
MySQL and MariaDB Backups
Federico Razzoli
 
JSON in MySQL and MariaDB Databases
Federico Razzoli
 
How MySQL can boost (or kill) your application v2
Federico Razzoli
 
Ad

Recently uploaded (20)

PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 

MariaDB, MySQL and Ansible: automating database infrastructures

  • 1. MariaDB, MySQL and Ansible: automating database infrastructures Federico Razzoli
  • 2. $ whoami Hi, I’m Federico Razzoli from Vettabase Ltd Database consultant, open source supporter, long time MariaDB and MySQL user ● vettabase.com ● Federico-Razzoli.com
  • 3. This talk ● General Ansible concepts ● Opinionated code examples, automating MariaDB/MySQL ● Good and bad practices
  • 5. What is Ansible ● A tool for deployment and configuration automation ● Infrastructure as code ● Idempotent ● Simple, non-centralised
  • 6. Ansible Concepts ● Inventory ● Module ● Playbook ● Role ● Play ● Variable ● Facts
  • 9. Ansible hosts [pmm] pmm-1 ansible_host=123.123.123.123 [mariadb_main] mariadb-main-1 ansible_host=123.0.0.1 mariadb-main-2 ansible_host=123.0.0.2 mariadb-main-3 ansible_host=123.0.0.3 [mariadb_main:vars] pmm_server_host=123.123.123.123 pmm_server_port=80 ● Sometimes we cannot use meaningful hostnames
  • 11. Groups goals ● You assign each group some roles ● You can deploy one or more group
  • 12. Multiple inventories production_db: [mariadb_master] mariadb-master-1 ansible_host=111.0.0.1 mariadb-master-2 ansible_host=111.0.0.2 staging_db: [mariadb_master] mariadb-master-1 ansible_host=222.0.0.1 mariadb-master-2 ansible_host=222.0.0.2
  • 13. Plays
  • 14. Play example --- - hosts: mariadb_main roles: - linux-for-mysql - mariadb - hosts: mysql_main roles: - linux-for-mysql - mysql ● You assign roles to groups (or individual hosts)
  • 15. Applying all roles to a certain host Call Ansible specifying an inventory and a play: % ansible-playbook -i staging -l mariadb_main main.yml
  • 16. Play example Here is where it can be convenient to have multiple inventories: % ansible-playbook -i staging -l mariadb_main main.yml % ansible-playbook -i production -l mariadb_main main.yml
  • 17. Roles, variables and templates
  • 18. Example - name: Create script dir file: name: "{{ script_dir }}" owner: root group: root mode: 755 state: directory ● This is a task, but the term is misleading ● A role is a list of tasks ● The name appears on screen ● "file" is the module ● script_dir is a variable
  • 19. Defining variables script_dir: /opt/scripts base_dir: /usr/local/mysql ... ● /host_vars/<host_name>.yml ● /group_vars/<group_name>.yml ● /roles/<role_name>/defaults/main.yml
  • 20. Notes on variables ● The same variable can be used by multiple roles ● Roles from Ansible Galaxy can’t use this opportunity ● This is a good reason to make your own roles ● Document what each variable does in README.md
  • 21. Copying a configuration file - name: Copy my.cnf copy: src: ./files/my.cnf dest: "/etc/mysql/{{ inventory_hostname }}.cnf" ● my.cnf is copied to /etc/mysql
  • 22. Using a template - name: Copy my.cnf template: src: ./templates/my.cnf .j2 dest: /etc/mysql/my.cnf ● This time my.cnf is a Jinja 2 template
  • 23. Template example [mysqld] user = mysql datadir = {{ mysql_data_dir }} innodb_buffer_pool_size = {{ innodb_buffer_pool_size }} ● This time my.cnf is a Jinja 2 template
  • 24. Problems ● If we want to set a variable, we should be able to add it in one place ○ host_vars or group_vars or role's defaults ● We can make a template more dynamic
  • 25. Dynamic template example In group_vars we create a list of dictionaries: (arrays of objects, if you prefer) group_mysql_variables: - { name: 'innodb_buffer_pool_size', value: '50G' } - { name: 'innodb_log_file_size', value: '50G' } In host_vars we optionally create another list: host_mysql_variables: - { name: 'innodb_buffer_pool_size', value: '80G' }
  • 26. Dynamic template example We loop over both the lists in the template: {% for var in group_mysql_variables %} {{ var.name }} = {{ var.value }} {% endfor %} {% if host_mysql_variables is defined %} {% for var in host_mysql_variables %} {{ var.name }} = {{ var.value }} {% endfor %} {% endif %}
  • 27. Notes ● We cannot use the same list in group_vars and host_vars, because the one in host_vars would overwrite the whole list ● Some variables may appear twice in the configuration file ● This is fine: the last occurrence of a variable will override the previous one
  • 28. Another use for lists Hosts of a cluster can be a list too: # print the IPs separated by commas wsrep_cluster_address = gcomm://{{ private_ips|join(',') }} # first node is the donor wsrep_sst_donor = {{ cluster_hosts[0].node_name }} # Only the first node imports a backup when the cluster is created - name: Import backup ... when: cluster_hosts[0] == hostvars[inventory_hostname]['ansible_default_ipv4']['address']
  • 29. Validate variables Validate variables for complex roles: - name: Validate cluster size assert: that: cluster_hosts|length > 0 fail_msg: cluster_hosts must contain at least 1 element success_msg: "cluster_hosts size: {{ cluster_hosts|length }}" - name: Validate cluster IPs assert: that: "'{{ item.public_ip }}'|ipaddr" fail_msg: "{{ item.public_ip }} is not a valid IP" success_msg: "{{ item.public_ip }}: OK" with_items: "{{ cluster_hosts }}"
  • 30. Tags and similar features
  • 31. Conditional tasks ● Certain tasks should only be run for certain servers: - name: Make server read only mysql_variables: variable: read_only value: 1 when: is_replica is sameas true ● Sometimes this avoids the need to create multiple roles which are very similar ● Instead of creating mariadb and mariadb_replica roles, we may create mariadb only, with some conditional tasks ○ Sometimes it makes sense, sometimes it doesn't
  • 32. Conditional tasks ● We can group optional tasks into separate files: - name: Make server read only include: replica.yml when: is_replica is sameas true
  • 33. Idempotency of Tasks ● Most modules are idempotent ● This means that you can run a task like this multiple times safely: - name: Start MariaDB service: state: started ● If the service is already running, nothing happens
  • 34. Idempotency of Tasks ● Sometimes you make non-idempotent tasks on purpose: - Copy my.cnf ... - name: Restart MariaDB service: state: restarted ● If the service is already running, nothing happens
  • 35. Idempotency of Tasks ● Sometimes you'd like a task to be idempotent, but it can't be: - name: Run a system command shell: > rm "{{ mysql_data_dir }}"/* - name: Run a script shell: > "{{ mysql_script_dir }}"/my_script.py - name: Run some SQL mysql_query: query: CREATE OR REPLACE TABLE db.table ( ... ); ● Ansible doesn't understand system commands, scripts or queries, so it has not way to check if they were already run. It runs them every time.
  • 36. Tags ● Ansible supports tags ● Each task can be assigned a list of tags: - name: (Re)create users ... - name: Update timezone info tags: [ tzinfo-update ] ... - name: Do something else ... ansible-playbook -i production_mysql --tag tzinfo-update production.yml
  • 37. Tags ● Typical tasks I want to have: - name: Do something - name: Copy my.cnf tags: [ mysql-config- static-update ] - name: Restart MySQL tags: [ mysql-config- static-update ] - name: Set variables at runtime tags: [ mysql-config- dynamic-update ] - name: Do something else
  • 38. Tags ● So there is a way to selectively run certain tasks ● But what if we want to selectively exclude certain tasks? ● There is not built-in way, but we can do something like this: - name: Do something - name: Restart MySQL service: state: restarted when: {{ mysql_restart }} is defined and {{ mysql_restart }} is sameas true - name: Do something else mething else ansible-playbook -i production_mysql --tag mysql-config-dynamic-update -e 'mysql_no_restart=1' production.yml
  • 41. Example CREATE OR REPLACE TABLE ticket ( id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, state ENUM('OPEN', 'VERIFIED', 'FIXED', 'INVALID') NOT NULL DEFAULT 'OPEN', summary VARCHAR(200) NOT NULL, description TEXT NOT NULL ) ENGINE InnoDB ; ● We want to start to track changes to bugs over time