### Start replication thread with mysql_replication Source: https://context7.com/ansible-collections/community.mysql/llms.txt Starts the replica I/O thread to begin replicating from the primary. `fail_on_error: true` will cause the task to fail if the thread cannot be started. ```yaml - name: Start replication community.mysql.mysql_replication: mode: startreplica fail_on_error: true login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Start MariaDB replica channel with mysql_replication Source: https://context7.com/ansible-collections/community.mysql/llms.txt Starts a specific replication channel on a MariaDB replica, identified by a connection name. Useful for multi-source replication setups. ```yaml - name: Start MariaDB replica channel primary-1 community.mysql.mysql_replication: mode: startreplica connection_name: primary-1 fail_on_error: true login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Prepare Development Environment Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Navigate into the cloned ansible repository and set up the development environment using the provided script and installing requirements. Then, change directory to your home. ```bash cd ansible && source hacking/env-setup pip install -r requirements.txt cd ~ ``` -------------------------------- ### Create a MySQL user with caching_sha2_password plugin and static salt Source: https://context7.com/ansible-collections/community.mysql/llms.txt This example demonstrates creating a MySQL user that uses the `caching_sha2_password` authentication plugin. A static salt is provided, which must be exactly 20 characters long. ```yaml - name: Create SHA2 auth user community.mysql.mysql_user: name: sha2user plugin: caching_sha2_password plugin_auth_string: "{{ sha2_password }}" salt: "abcdefghij1234567890" # must be exactly 20 chars priv: 'mydb.*:SELECT' state: present login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Install Ansible Collection Source: https://context7.com/ansible-collections/community.mysql/llms.txt Install the community.mysql collection using ansible-galaxy. Use a requirements.yml file to pin a specific version for reproducible deployments. ```bash ansible-galaxy collection install community.mysql ``` ```yaml # requirements.yml collections: - name: community.mysql version: ">=4.2.0" ``` ```bash ansible-galaxy collection install -r requirements.yml ``` -------------------------------- ### Install Community MySQL Ansible Collection Source: https://github.com/ansible-collections/community.mysql/blob/main/README.md Install the community.mysql collection using the Ansible Galaxy CLI. This is the primary method for obtaining the collection. ```bash ansible-galaxy collection install community.mysql ``` -------------------------------- ### Install Specific Version of Community MySQL Ansible Collection Source: https://github.com/ansible-collections/community.mysql/blob/main/README.md Install a specific version of the community.mysql collection, useful for downgrading if a newer version introduces issues. Replace '2.0.0' with the desired version. ```bash ansible-galaxy collection install community.mysql:==2.0.0 ``` -------------------------------- ### Ansible Collection Plugin Directory Structure Source: https://github.com/ansible-collections/community.mysql/blob/main/plugins/README.md This example shows the standard directory organization for different types of Ansible plugins within a collection. It includes common plugin types and directories for module utilities and modules. ```directory └── plugins ├── action ├── become ├── cache ├── callback ├── cliconf ├── connection ├── filter ├── httpapi ├── inventory ├── lookup ├── module_utils ├── modules ├── netconf ├── shell ├── strategy ├── terminal ├── test └── vars ``` -------------------------------- ### Install Community MySQL Ansible Collection via requirements.yml Source: https://github.com/ansible-collections/community.mysql/blob/main/README.md Include the community.mysql collection in your Ansible project by defining it in a requirements.yml file. This ensures consistent installation across environments. ```yaml --- collections: - name: community.mysql ``` -------------------------------- ### Run Sanity Tests Locally Source: https://github.com/ansible-collections/community.mysql/blob/main/CONTRIBUTING.md Execute sanity tests on a specific file to check for common issues before pushing changes. Ensure your local environment is prepared as per the development guide. ```console $ ansible-test sanity path/to/changed_file.py --docker -v ``` -------------------------------- ### Get primary binlog status with mysql_replication Source: https://context7.com/ansible-collections/community.mysql/llms.txt Retrieves the current primary binlog file and position. This information is often needed to configure replicas. ```yaml - name: Get primary status community.mysql.mysql_replication: mode: getprimary login_unix_socket: /run/mysqld/mysqld.sock register: primary_status ``` -------------------------------- ### Create a read-only reporting role in MySQL Source: https://context7.com/ansible-collections/community.mysql/llms.txt This example creates a MySQL role named 'readers' that grants read-only SELECT privileges on both 'appdb' and 'reporting' databases. ```yaml # Create a read-only reporting role - name: Create readers role community.mysql.mysql_role: name: readers state: present priv: 'appdb.*': 'SELECT' 'reporting.*': 'SELECT' login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Configure replica with GTID using mysql_replication Source: https://context7.com/ansible-collections/community.mysql/llms.txt Configures a replica to use GTID (Global Transaction Identifiers) for automatic positioning. This simplifies replica setup and failover. ```yaml - name: Configure replica with GTID community.mysql.mysql_replication: mode: changeprimary primary_host: "10.0.0.1" primary_user: repl primary_password: "{{ repl_password }}" primary_auto_position: true login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Nest a role inside another role in MySQL Source: https://context7.com/ansible-collections/community.mysql/llms.txt This example demonstrates nesting one role ('marketing') within another ('business') by specifying the role name in the `members` list. This creates a hierarchical role structure. ```yaml # Nest a role inside another role - name: Create business role containing marketing role community.mysql.mysql_role: name: business state: present members: - marketing # role name without host login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Set custom user attributes in MySQL (8.0+) Source: https://context7.com/ansible-collections/community.mysql/llms.txt This example shows how to tag a MySQL user with custom attributes, such as team and oncall status, using the `attributes` parameter. This feature requires MySQL 8.0 or later. ```yaml - name: Tag user with team metadata community.mysql.mysql_user: name: bob attributes: team: "backend" oncall: "yes" login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Detach a single member from a role in MySQL Source: https://context7.com/ansible-collections/community.mysql/llms.txt This example removes a specific member ('bob@localhost') from the 'developers' role without affecting other members. Use `detach_members: true` to remove specific members. ```yaml # Detach a single member without affecting others - name: Remove bob from developers community.mysql.mysql_role: name: developers state: present detach_members: true members: - 'bob@localhost' login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Configure replica using binlog position with mysql_replication Source: https://context7.com/ansible-collections/community.mysql/llms.txt Configures a replica to follow a primary using the binlog file and position obtained from `getprimary` mode. Ensure `repl_password` is defined. ```yaml - name: Configure replica community.mysql.mysql_replication: mode: changeprimary primary_host: "10.0.0.1" primary_user: repl primary_password: "{{ repl_password }}" primary_port: 3306 primary_log_file: "{{ primary_status.File }}" primary_log_pos: "{{ primary_status.Position }}" login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Navigate to Collection Directory Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Change the current directory to your newly cloned community.mysql repository. ```bash cd ~/ansible_collections/community/mysql ``` -------------------------------- ### Create Collection Directory Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Create the necessary directory structure in your home directory for the community.mysql collection. ```bash mkdir -p ~/ansible_collections/community/mysql ``` -------------------------------- ### Collect Specific Server Information (Version and Databases) Source: https://context7.com/ansible-collections/community.mysql/llms.txt Gathers only the server version and database names, excluding database sizes for performance. Allows returning empty databases if none exist. ```yaml # Collect only version and database names - name: Get version and databases community.mysql.mysql_info: filter: - version - databases exclude_fields: - db_size # skip slow size calculation return_empty_dbs: true login_unix_socket: /run/mysqld/mysqld.sock register: basic_info ``` -------------------------------- ### Execute Simple SELECT Query with Unix Socket Source: https://context7.com/ansible-collections/community.mysql/llms.txt Fetches open orders from the 'appdb' database using a Unix socket for authentication. The query result is registered in the 'open_orders' variable. ```yaml - name: Fetch open orders community.mysql.mysql_query: login_db: appdb query: SELECT id, status FROM orders WHERE status = 'open' login_unix_socket: /run/mysqld/mysqld.sock register: open_orders ``` -------------------------------- ### Run All Makefile Targets Source: https://github.com/ansible-collections/community.mysql/blob/main/TESTING.md Execute all defined test targets using the Makefile. Specify Ansible version, database engine, and connector details. ```sh make ansible="stable-2.16" db_engine_name="mysql" db_engine_version="8.0.31" connector_name="pymysql" connector_version="1.0.2" ``` -------------------------------- ### Run Unit Tests Locally Source: https://github.com/ansible-collections/community.mysql/blob/main/CONTRIBUTING.md Execute unit tests for a specific Python file to verify the correctness of individual components. This command requires the Docker environment to be set up. ```console $ ansible-test units tests/unit/plugins/unit_test_file.py --docker ``` -------------------------------- ### Create a fully-privileged admin user in MySQL Source: https://context7.com/ansible-collections/community.mysql/llms.txt Use this to create a new MySQL user with all privileges on all databases. Ensure the password variable is defined. ```yaml - name: Create admin user bob community.mysql.mysql_user: name: bob password: "{{ bob_password }}" priv: '*.*:ALL,GRANT' state: present login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Gather All Server Information Source: https://context7.com/ansible-collections/community.mysql/llms.txt Collects comprehensive server metadata including version, databases, users, settings, status, storage engines, and replication status. Requires root privileges and access via Unix socket. ```yaml # Collect all available server information - name: Gather full server info community.mysql.mysql_info: login_user: root login_unix_socket: /run/mysqld/mysqld.sock register: db_info ``` -------------------------------- ### Execute Parameterized SELECT with Named Arguments Source: https://context7.com/ansible-collections/community.mysql/llms.txt Fetches orders based on status and creation date using named arguments for query parameters. The query string uses %(key)s syntax. ```yaml - name: Fetch orders with named parameters community.mysql.mysql_query: login_db: appdb query: > SELECT * FROM orders WHERE status = %(status)s AND created_at > %(since)s named_args: status: shipped since: "2024-01-01" login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Configure SSL replica with mysql_replication Source: https://context7.com/ansible-collections/community.mysql/llms.txt Configures a replica to connect to the primary using SSL encryption. Requires specifying SSL certificates and verification options. ```yaml - name: Configure SSL replica community.mysql.mysql_replication: mode: changeprimary primary_host: "10.0.0.1" primary_user: repl primary_password: "{{ repl_password }}" primary_ssl: true primary_ssl_ca: /etc/ssl/mysql/ca.pem primary_ssl_verify_server_cert: true primary_auto_position: true login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### View Git Remotes Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Check the configured remote repositories. Initially, only 'origin' should be present. ```bash git remote -v ``` -------------------------------- ### Community MySQL Replication Module Source: https://context7.com/ansible-collections/community.mysql/llms.txt Manage MySQL/MariaDB replication configurations, including setting up primaries, replicas, and monitoring status. ```APIDOC ## Get primary status ### Description Retrieves the current primary binlog file and position. ### Method community.mysql.mysql_replication ### Parameters #### Mode - **mode** (str) - Required - Set to 'getprimary' to retrieve primary status. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ### Response Example ```json { "File": "mysql-bin.000023", "Position": 4578 } ``` ## Configure replica using binlog position ### Description Configures a replica to follow a primary using the binlog file and position. ### Method community.mysql.mysql_replication ### Parameters #### Mode - **mode** (str) - Required - Set to 'changeprimary' to configure replica. #### Primary Connection - **primary_host** (str) - Required - Hostname or IP address of the primary server. - **primary_user** (str) - Required - Username for connecting to the primary. - **primary_password** (str) - Required - Password for connecting to the primary. - **primary_port** (int) - Optional - Port number of the primary server. #### Binlog Coordinates - **primary_log_file** (str) - Required - The binlog file name from the primary. - **primary_log_pos** (int) - Required - The position within the binlog file. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ## Configure replica with GTID (MySQL) ### Description Configures a replica to follow a primary using GTID auto-position. ### Method community.mysql.mysql_replication ### Parameters #### Mode - **mode** (str) - Required - Set to 'changeprimary' to configure replica. #### Primary Connection - **primary_host** (str) - Required - Hostname or IP address of the primary server. - **primary_user** (str) - Required - Username for connecting to the primary. - **primary_password** (str) - Required - Password for connecting to the primary. #### GTID Configuration - **primary_auto_position** (bool) - Required - Set to true to use GTID auto-position. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ## Configure MariaDB replica with GTID current_pos ### Description Configures a MariaDB replica to follow a primary using GTID `current_pos`. ### Method community.mysql.mysql_replication ### Parameters #### Mode - **mode** (str) - Required - Set to 'changeprimary' to configure replica. #### Primary Connection - **primary_host** (str) - Required - Hostname or IP address of the primary server. - **primary_user** (str) - Required - Username for connecting to the primary. - **primary_password** (str) - Required - Password for connecting to the primary. #### GTID Configuration - **primary_use_gtid** (str) - Required - Set to 'current_pos' for MariaDB GTID. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ## Start replication thread ### Description Starts the replication thread on the replica server. ### Method community.mysql.mysql_replication ### Parameters #### Mode - **mode** (str) - Required - Set to 'startreplica' to start the replication thread. #### Error Handling - **fail_on_error** (bool) - Optional - If true, the task will fail if an error occurs during startup. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ## Check replica status ### Description Retrieves the status of the replica replication threads. ### Method community.mysql.mysql_replication ### Parameters #### Mode - **mode** (str) - Required - Set to 'getreplica' to retrieve replica status. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ### Response Example ```json { "Slave_IO_Running": "Yes", "Slave_SQL_Running": "Yes" } ``` ## Gracefully stop replica for maintenance ### Description Stops the replica replication threads gracefully, typically before performing maintenance. ### Method community.mysql.mysql_replication ### Parameters #### Mode - **mode** (str) - Required - Set to 'stopreplica' to stop the replication threads. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ## Multi-source: start a named connection (MariaDB) ### Description Starts a named replication channel on a MariaDB replica. ### Method community.mysql.mysql_replication ### Parameters #### Mode - **mode** (str) - Required - Set to 'startreplica' to start a replication channel. #### Connection Details - **connection_name** (str) - Required - The name of the replication channel to start. #### Error Handling - **fail_on_error** (bool) - Optional - If true, the task will fail if an error occurs. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ## Multi-source: stop a MySQL replication channel ### Description Stops a specific MySQL replication channel. ### Method community.mysql.mysql_replication ### Parameters #### Mode - **mode** (str) - Required - Set to 'stopreplica' to stop a replication channel. #### Channel - **channel** (str) - Required - The name of the replication channel to stop. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ## Configure SSL replica ### Description Configures a replica to connect to the primary using SSL encryption. ### Method community.mysql.mysql_replication ### Parameters #### Mode - **mode** (str) - Required - Set to 'changeprimary' to configure replica. #### Primary Connection - **primary_host** (str) - Required - Hostname or IP address of the primary server. - **primary_user** (str) - Required - Username for connecting to the primary. - **primary_password** (str) - Required - Password for connecting to the primary. #### SSL Configuration - **primary_ssl** (bool) - Required - Enable SSL for the connection. - **primary_ssl_ca** (str) - Optional - Path to the CA certificate file. - **primary_ssl_verify_server_cert** (bool) - Optional - Whether to verify the primary's server certificate. #### GTID Configuration - **primary_auto_position** (bool) - Required - Set to true to use GTID auto-position. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ``` -------------------------------- ### Create New Branch Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Create a new branch for your feature or bug fix. Replace 'name_of_my_branch' with a descriptive name. ```bash git checkout -b name_of_my_branch ``` -------------------------------- ### Create a role with full DB privileges and assign members in MySQL Source: https://context7.com/ansible-collections/community.mysql/llms.txt This task creates a new MySQL role named 'developers' with full privileges on 'appdb' and assigns 'alice@%' and 'bob@localhost' as members. `SET DEFAULT ROLE ALL` is automatically executed for the assigned members. ```yaml # Create a role with full DB privileges and assign members - name: Create developers role community.mysql.mysql_role: name: developers state: present priv: 'appdb.*:ALL' members: - 'alice@%' - 'bob@localhost' login_unix_socket: /run/mysqld/mysqld.sock # SET DEFAULT ROLE ALL is automatically run for alice and bob ``` -------------------------------- ### Write to mysqld-auto.cnf for next restart with mysql_variables Source: https://context7.com/ansible-collections/community.mysql/llms.txt Writes a variable change to `mysqld-auto.cnf` for the next server restart only, without altering the current runtime value. Useful for pre-configuring settings. ```yaml # Write to mysqld-auto.cnf without changing runtime value (next restart only) - name: Pre-configure innodb_buffer_pool_size for next restart community.mysql.mysql_variables: variable: innodb_buffer_pool_size value: "4294967296" # 4 GB mode: persist_only login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Common Connection Parameters for MySQL Modules Source: https://context7.com/ansible-collections/community.mysql/llms.txt All community.mysql modules accept a uniform set of connection parameters. These can be provided inline or read from a configuration file like ~/.my.cnf. TLS parameters are also supported. ```yaml # All modules accept these connection parameters: - name: Example showing all connection options community.mysql.mysql_info: login_user: admin login_password: "{{ vault_db_password }}" login_host: db.example.com login_port: 3306 login_unix_socket: /var/run/mysqld/mysqld.sock # preferred for localhost connect_timeout: 30 config_file: /home/deploy/.my.cnf # defaults to ~/.my.cnf ca_cert: /etc/ssl/mysql/ca.pem client_cert: /etc/ssl/mysql/client-cert.pem client_key: /etc/ssl/mysql/client-key.pem check_hostname: true filter: version ``` -------------------------------- ### Manage MySQL Databases with mysql_db Source: https://context7.com/ansible-collections/community.mysql/llms.txt Use the mysql_db module to create, remove, dump, or import MySQL/MariaDB databases. Supports compressed files, encoding, collation, and transaction safety. Use `state: dump` for backups and `state: import` for restores. ```yaml # Create a UTF-8 database - name: Create application database community.mysql.mysql_db: name: appdb state: present encoding: utf8mb4 collation: utf8mb4_unicode_ci login_unix_socket: /run/mysqld/mysqld.sock ``` ```yaml # Create multiple databases at once - name: Create staging and test databases community.mysql.mysql_db: name: - staging_db - test_db state: present encoding: utf8mb4 login_user: root login_password: "{{ root_password }}" ``` ```yaml # Dump a single database to a gzip-compressed file, catching pipe errors - name: Backup appdb community.mysql.mysql_db: state: dump name: appdb target: /backups/appdb-{{ ansible_date_time.date }}.sql.gz single_transaction: true quick: true pipefail: true login_unix_socket: /run/mysqld/mysqld.sock ``` ```yaml # Dump all databases including binary log position for replica setup - name: Full server backup with master data community.mysql.mysql_db: state: dump name: all target: /backups/full-backup.sql.gz master_data: 1 single_transaction: true ignore_tables: - appdb.cache_entries - appdb.sessions login_unix_socket: /run/mysqld/mysqld.sock ``` ```yaml # Restore a compressed dump, creating the database if absent - name: Restore appdb from backup community.mysql.mysql_db: state: import name: appdb target: /backups/appdb-2024-06-01.sql.gz force: true login_unix_socket: /run/mysqld/mysqld.sock ``` ```yaml # Import with a specific encoding - name: Import legacy Latin-1 dump community.mysql.mysql_db: state: import name: legacy_db target: /tmp/legacy.sql encoding: latin1 use_shell: true login_unix_socket: /run/mysqld/mysqld.sock ``` ```yaml # Remove databases - name: Drop test databases community.mysql.mysql_db: name: - test_db - staging_db state: absent login_unix_socket: /run/mysqld/mysqld.sock # Returns: { changed: true, db: "test_db staging_db", db_list: ["test_db","staging_db"], # executed_commands: ["DROP DATABASE `test_db`", "DROP DATABASE `staging_db`"] } ``` -------------------------------- ### Run Single Makefile Target Source: https://github.com/ansible-collections/community.mysql/blob/main/TESTING.md Execute a specific test target using the Makefile. Useful for faster testing of individual components. Requires specifying Ansible version, database engine, and connector details. ```sh make ansible="stable-2.16" db_engine_name="mysql" db_engine_version="8.0.31" connector_name="pymysql" connector_version="1.0.2" target="test_mysql_info" ``` -------------------------------- ### Run All Tests Script Source: https://github.com/ansible-collections/community.mysql/blob/main/TESTING.md Execute the `run_all_tests.py` script to replicate the GitHub Actions test matrix. This script runs all combinations of MySQL, MariaDB, and Connector tests. ```python python run_all_tests.py ``` -------------------------------- ### Clone Forked Repository (HTTPS) Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Clone your forked community.mysql repository into the designated path using HTTPS. Replace YOURACC with your GitHub username. ```bash git clone https://github.com/YOURACC/community.mysql.git ~/ansible_collections/community/mysql ``` -------------------------------- ### Run Integration Tests Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Execute integration tests for a specific module (e.g., mysql_user) using Docker. The -vvv flag provides verbose output for debugging. ```bash ansible-test integration test_mysql_user --docker -vvv ``` -------------------------------- ### Run Integration Tests Source: https://github.com/ansible-collections/community.mysql/wiki/Testing-your-changes Execute integration tests for a specific target, Ansible version, database engine, Python version, and connector. Adjust `target` to the desired test suite. ```sh make \ ansible="stable-2.14" \ db_engine_name="mariadb" \ db_engine_version="10.6.11" \ python="3.9" \ connector_name="pymysql" \ connector_version="0.9.3" \ target="test_mysql_query" ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing After adding a changelog fragment, commit the changes and push them to your origin branch. This action triggers CI tests. ```bash git add changelog/fragments/myfragment.yml git commit -m "Add changelog fragment" git push origin name_of_my_branch ``` -------------------------------- ### Clone Users from Source to Target Server Source: https://context7.com/ansible-collections/community.mysql/llms.txt Fetches user information from a source MySQL server and then recreates those users on a target server using the 'mysql_user' module. Excludes system users like 'root'. ```yaml # Clone users from a source server to a target server - name: Fetch users_info from source delegate_to: db_source community.mysql.mysql_info: filter: - users_info login_unix_socket: /run/mysqld/mysqld.sock register: source_users - name: Recreate users on target community.mysql.mysql_user: name: "{{ item.name }}" host: "{{ item.host }}" plugin: "{{ item.plugin | default(omit) }}" plugin_hash_string: "{{ item.plugin_hash_string | default(omit) }}" tls_requires: "{{ item.tls_requires | default(omit) }}" priv: "{{ item.priv | default(omit) }}" resource_limits: "{{ item.resource_limits | default(omit) }}" column_case_sensitive: true state: present login_unix_socket: /run/mysqld/mysqld.sock loop: "{{ source_users.users_info }}" loop_control: label: "{{ item.name }}@{{ item.host }}" when: item.name not in ['root', 'mysql', 'mariadb.sys'] ``` -------------------------------- ### Secure an external MySQL user with TLS and resource limits Source: https://context7.com/ansible-collections/community.mysql/llms.txt This task configures an external MySQL user with TLS requirements, resource limits (queries and connections per hour), and password expiration. The user can connect from any host (`%`). ```yaml - name: Secure external user community.mysql.mysql_user: name: external_user host: "%" password: "{{ ext_password }}" priv: 'reporting.*:SELECT' tls_requires: x509: resource_limits: MAX_QUERIES_PER_HOUR: 1000 MAX_CONNECTIONS_PER_HOUR: 20 password_expire: interval password_expire_interval: 90 state: present login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Clone Forked Repository (SSH) Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Clone your forked community.mysql repository into the designated path using SSH. Replace YOURACC with your GitHub username. ```bash git clone git@github.com:YOURACC/community.mysql.git ~/ansible_collections/community/mysql ``` -------------------------------- ### Makefile with Debugging Options Source: https://github.com/ansible-collections/community.mysql/blob/main/TESTING.md Run tests with options to keep containers alive for debugging and to continue execution on errors. This is useful for diagnosing issues by allowing inspection of containers. ```sh make ansible="stable-2.17" db_engine_name="mysql" db_engine_version="8.0.31" connector_name="pymysql" connector_version="1.0.2" target="test_mysql_query" keep_containers_alive=1 continue_on_errors=1 ``` -------------------------------- ### Clone Ansible Repository Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Clone the ansible-core repository to set up the development environment. This is a prerequisite for working with the collection. ```bash git clone https://github.com/ansible/ansible.git ``` -------------------------------- ### Add Upstream Remote Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Add the official community.mysql repository as an 'upstream' remote to fetch changes from. ```bash git remote add upstream https://github.com/ansible-collections/community.mysql.git ``` -------------------------------- ### Execute Parameterized SELECT with Positional Arguments Source: https://context7.com/ansible-collections/community.mysql/llms.txt Fetches a specific order by ID and customer using positional arguments for the query parameters. Requires 'positional_args' to be a list. ```yaml - name: Fetch order by ID and customer community.mysql.mysql_query: login_db: appdb query: SELECT * FROM orders WHERE id = %s AND customer_id = %s positional_args: - 42 - 7 login_unix_socket: /run/mysqld/mysqld.sock register: order_result ``` -------------------------------- ### Create an application user with specific database privileges in MySQL Source: https://context7.com/ansible-collections/community.mysql/llms.txt This snippet creates a MySQL user for application use, granting specific SELECT, INSERT, UPDATE, DELETE privileges on designated databases. The `update_password: on_create` ensures the password is not rotated on subsequent runs. ```yaml - name: Create app service account community.mysql.mysql_user: name: appuser host: "192.168.1. %" password: "{{ app_password }}" priv: 'appdb.*': 'SELECT,INSERT,UPDATE,DELETE' 'appdb_readonly.*': 'SELECT' update_password: on_create # do not rotate password on subsequent runs state: present login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Check Git Status Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Verify that you are on the main branch of your local repository. ```bash git status ``` -------------------------------- ### Common Connection Parameters Source: https://context7.com/ansible-collections/community.mysql/llms.txt All modules in the community.mysql collection share a common set of connection parameters for establishing a connection to the MySQL/MariaDB server. These include user credentials, host, port, socket, configuration file path, and TLS settings. ```APIDOC ## Common connection parameters (shared by all modules) Every module in the collection inherits the `community.mysql.mysql` doc fragment, which exposes a uniform set of connection options. ```yaml # All modules accept these connection parameters: - name: Example showing all connection options community.mysql.mysql_info: login_user: admin login_password: "{{ vault_db_password }}" login_host: db.example.com login_port: 3306 login_unix_socket: /var/run/mysqld/mysqld.sock # preferred for localhost connect_timeout: 30 config_file: /home/deploy/.my.cnf # defaults to ~/.my.cnf ca_cert: /etc/ssl/mysql/ca.pem client_cert: /etc/ssl/mysql/client-cert.pem client_key: /etc/ssl/mysql/client-key.pem check_hostname: true filter: version ``` ``` -------------------------------- ### Commit Changes Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Stage the changed file and commit your modifications with an informative message. Replace '/path/to/changed/file' with the actual file path. ```bash git add /path/to/changed/file git commit -m "mysql_user: fix crash when ..." ``` -------------------------------- ### Push Branch to Origin Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Push your local branch with the committed changes to your fork on the 'origin' remote. ```bash git push origin name_of_my_branch ``` -------------------------------- ### Run Sanity Tests Source: https://github.com/ansible-collections/community.mysql/wiki/Testing-your-changes Execute sanity tests for a specific Python module using Docker. Ensure the default Docker container is used with the `--docker` or `--docker default` option. ```sh ansible-test sanity plugins/modules/mysql_query.py --docker --docker-no-pull ``` -------------------------------- ### Create a replication user in MySQL Source: https://context7.com/ansible-collections/community.mysql/llms.txt This task creates a MySQL user specifically for replication purposes, granting `REPLICATION SLAVE` and `REPLICATION CLIENT` privileges. The host is restricted to a specific network range. ```yaml - name: Create replication user community.mysql.mysql_user: name: repl host: "10.0.0. %" password: "{{ repl_password }}" priv: "*.*:REPLICATION SLAVE,REPLICATION CLIENT" state: present login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Community MySQL Variables Module Source: https://context7.com/ansible-collections/community.mysql/llms.txt Query and set global MySQL/MariaDB server variables, with options for runtime changes and persistence. ```APIDOC ## mysql_variables — Query and set global server variables ### Description `mysql_variables` reads or sets MySQL/MariaDB global variables at runtime, with optional persistence across server restarts via `persist` and `persist_only` modes (MySQL 8.0+). ## Read a variable value ### Description Reads the current value of a specified global server variable. ### Method community.mysql.mysql_variables ### Parameters #### Variable - **variable** (str) - Required - The name of the variable to read. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ### Response Example ```json { "msg": "1" } ``` ## Set a variable at runtime (not persisted) ### Description Sets a global server variable for the current runtime session. The change will not survive a server restart. ### Method community.mysql.mysql_variables ### Parameters #### Variable - **variable** (str) - Required - The name of the variable to set. - **value** (str) - Required - The desired value for the variable. - **mode** (str) - Optional - Set to 'global' to modify the global variable. Defaults to 'global'. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ## Set and persist a variable (MySQL 8.0+) ### Description Sets a global server variable and persists the change so it survives server restarts. ### Method community.mysql.mysql_variables ### Parameters #### Variable - **variable** (str) - Required - The name of the variable to set. - **value** (str) - Required - The desired value for the variable. - **mode** (str) - Required - Set to 'persist' to save the change across restarts. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ### Response Example ```json { "queries": ["SET PERSIST `max_connections` = 500"] } ``` ## Write to mysqld-auto.cnf without changing runtime value (next restart only) ### Description Configures a variable in `mysqld-auto.cnf` so that the change takes effect on the next server restart, without altering the current runtime value. ### Method community.mysql.mysql_variables ### Parameters #### Variable - **variable** (str) - Required - The name of the variable to configure. - **value** (str) - Required - The desired value for the variable. - **mode** (str) - Required - Set to 'persist_only' to configure for the next restart. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ## Set read_only mode on replica ### Description Enables or disables the read-only mode on a replica server. ### Method community.mysql.mysql_variables ### Parameters #### Variable - **variable** (str) - Required - Set to 'read_only' to control read-only mode. - **value** (str) - Required - Set to '1' to enable read-only mode, '0' to disable. - **mode** (str) - Optional - Set to 'global' to modify the global variable. Defaults to 'global'. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ## Set long_query_time for slow query logging ### Description Sets the threshold for logging slow queries. ### Method community.mysql.mysql_variables ### Parameters #### Variable - **variable** (str) - Required - Set to 'long_query_time' to configure the slow query threshold. - **value** (str) - Required - The time in seconds to consider a query slow. - **mode** (str) - Required - Set to 'persist' to save the change across restarts. #### Login - **login_unix_socket** (str) - Optional - Path to the MySQL login socket. ``` -------------------------------- ### Run Sanity Tests Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Execute sanity tests on a specific Python file using Docker. This checks for code formatting and documentation standards. ```bash ansible-test sanity plugins/modules/mysql_user.py --docker ``` -------------------------------- ### Set and persist a global server variable with mysql_variables Source: https://context7.com/ansible-collections/community.mysql/llms.txt Sets a global MySQL/MariaDB server variable and persists the change so it survives server restarts. Requires MySQL 8.0+. The output shows the `SET PERSIST` query executed. ```yaml # Set and persist a variable so it survives restarts (MySQL 8.0+) - name: Persist max_connections community.mysql.mysql_variables: variable: max_connections value: "500" mode: persist login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### mysql_db — Manage databases, dump, and import Source: https://context7.com/ansible-collections/community.mysql/llms.txt The `mysql_db` module manages the lifecycle of MySQL/MariaDB databases, including creation, deletion, and performing dump and import operations. It supports compressed files, character sets, collations, and transaction safety. ```APIDOC ## mysql_db — Manage databases, dump, and import `mysql_db` creates or removes databases and handles dump/import operations with support for compressed files (`.gz`, `.bz2`, `.xz`, `.zst`), encoding, collation, and transaction safety. ```yaml # Create a UTF-8 database - name: Create application database community.mysql.mysql_db: name: appdb state: present encoding: utf8mb4 collation: utf8mb4_unicode_ci login_unix_socket: /run/mysqld/mysqld.sock # Create multiple databases at once - name: Create staging and test databases community.mysql.mysql_db: name: - staging_db - test_db state: present encoding: utf8mb4 login_user: root login_password: "{{ root_password }}" # Dump a single database to a gzip-compressed file, catching pipe errors - name: Backup appdb community.mysql.mysql_db: state: dump name: appdb target: /backups/appdb-{{ ansible_date_time.date }}.sql.gz single_transaction: true quick: true pipefail: true login_unix_socket: /run/mysqld/mysqld.sock # Dump all databases including binary log position for replica setup - name: Full server backup with master data community.mysql.mysql_db: state: dump name: all target: /backups/full-backup.sql.gz master_data: 1 single_transaction: true ignore_tables: - appdb.cache_entries - appdb.sessions login_unix_socket: /run/mysqld/mysqld.sock # Restore a compressed dump, creating the database if absent - name: Restore appdb from backup community.mysql.mysql_db: state: import name: appdb target: /backups/appdb-2024-06-01.sql.gz force: true login_unix_socket: /run/mysqld/mysqld.sock # Import with a specific encoding - name: Import legacy Latin-1 dump community.mysql.mysql_db: state: import name: legacy_db target: /tmp/legacy.sql encoding: latin1 use_shell: true login_unix_socket: /run/mysqld/mysqld.sock # Remove databases - name: Drop test databases community.mysql.mysql_db: name: - test_db - staging_db state: absent login_unix_socket: /run/mysqld/mysqld.sock # Returns: { changed: true, db: "test_db staging_db", db_list: ["test_db","staging_db"], # executed_commands: ["DROP DATABASE `test_db`", "DROP DATABASE `staging_db`"] ``` ``` -------------------------------- ### Run Flake8 Linter Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Check a specific Python file for style issues and unused imports using the flake8 linter. This is a preliminary check before running full sanity tests. ```bash flake8 plugins/modules/mysql_user.py ``` -------------------------------- ### Create a locked MySQL user as procedure definer Source: https://context7.com/ansible-collections/community.mysql/llms.txt This task creates a locked MySQL user that can act as a procedure definer. The user is granted specific privileges on `appdb` and is set to `locked: true`. ```yaml - name: Create locked definer account community.mysql.mysql_user: name: proc_definer locked: true priv: appdb.*: 'SELECT,EXECUTE' state: present login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Set a global server variable at runtime with mysql_variables Source: https://context7.com/ansible-collections/community.mysql/llms.txt Sets a global MySQL/MariaDB server variable at runtime. This change is not persisted across server restarts. ```yaml # Set a variable at runtime (not persisted) - name: Enable slow query log community.mysql.mysql_variables: variable: slow_query_log value: "ON" mode: global login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Makefile with Local Python Version Source: https://github.com/ansible-collections/community.mysql/blob/main/TESTING.md Use this option when your system's default Python version is unsupported by the Ansible version being tested. Specify a compatible local Python version. ```sh make local_python_version="3.10" ansible="stable-2.17" db_engine_name="mariadb" db_engine_version="11.4.5" connector_name="pymysql" connector_version="1.0.2" ``` -------------------------------- ### Create Table if Absent using DDL Source: https://context7.com/ansible-collections/community.mysql/llms.txt Ensures the 'audit_log' table exists in the 'appdb' database using a 'CREATE TABLE IF NOT EXISTS' statement. This is useful for idempotent schema management. ```yaml - name: Ensure audit_log table exists community.mysql.mysql_query: login_db: appdb query: > CREATE TABLE IF NOT EXISTS audit_log ( id INT AUTO_INCREMENT PRIMARY KEY, action VARCHAR(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Configure MariaDB replica with GTID using mysql_replication Source: https://context7.com/ansible-collections/community.mysql/llms.txt Configures a MariaDB replica to use GTID with the `current_pos` option. This is specific to MariaDB's GTID implementation. ```yaml - name: Configure MariaDB replica with GTID community.mysql.mysql_replication: mode: changeprimary primary_host: "10.0.0.1" primary_user: repl primary_password: "{{ repl_password }}" primary_use_gtid: current_pos login_unix_socket: /run/mysqld/mysqld.sock ``` -------------------------------- ### Check replica status with mysql_replication Source: https://context7.com/ansible-collections/community.mysql/llms.txt Retrieves the current status of the replica threads. This is useful for verifying if replication is running correctly. ```yaml - name: Verify replication is running community.mysql.mysql_replication: mode: getreplica login_unix_socket: /run/mysqld/mysqld.sock register: replica_status ``` -------------------------------- ### mysql_user — Manage database users and privileges Source: https://context7.com/ansible-collections/community.mysql/llms.txt The `mysql_user` module is used to create, modify, and remove MySQL/MariaDB user accounts. It supports managing user passwords, authentication methods, TLS requirements, privilege grants, resource limits, and password expiration policies. ```APIDOC ## mysql_user — Manage database users and privileges `mysql_user` creates, modifies, or removes MySQL/MariaDB user accounts including passwords, authentication plugins, TLS requirements, privilege grants, resource limits, and password expiry policies. ```yaml ``` -------------------------------- ### Update Local Main Branch Source: https://github.com/ansible-collections/community.mysql/wiki/Contributing Fetch changes from the upstream repository and rebase your local main branch to stay up-to-date. ```bash git fetch upstream git rebase upstream/main ``` -------------------------------- ### Audit Databases and Users Excluding Settings Source: https://context7.com/ansible-collections/community.mysql/llms.txt Collects server audit data including databases and users, but excludes the 'settings' subset to reduce data volume. Requires specific user credentials. ```yaml # Collect all info except heavy settings dump - name: Audit databases and users community.mysql.mysql_info: filter: "!settings" login_user: auditor login_password: "{{ auditor_password }}" login_host: db.example.com register: audit_data ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.