Ansible idempotent MySQL installation Playbook

后端 未结 11 1405
后悔当初
后悔当初 2021-01-30 04:29

I want to setup a MySQL server on AWS, using Ansible for the configuration management. I am using the default AMI from Amazon (ami-3275ee5b), which uses yum

11条回答
  •  悲哀的现实
    2021-01-30 04:45

    Well, this came a bit complicated. I've spent a whole day on this and came up with the solution listed below. The key point is how Ansible installs MySQL server. From the docs of mysql_user module (last note on page):

    MySQL server installs with default login_user of ‘root’ and no password. To secure this user as part of an idempotent playbook, you must create at least two tasks: the first must change the root user’s password, without providing any login_user/login_password details. The second must drop a ~/.my.cnf file containing the new root credentials. Subsequent runs of the playbook will then succeed by reading the new credentials from the file.
    

    That issue with blank or null password was a big surprise.

    Role:

    ---
    
    - name: Install MySQL packages
      sudo: yes
      yum: name={{ item }} state=present
      with_items:
        - mysql
        - mysql-server
        - MySQL-python
    
    
    - name: Start MySQL service
      sudo: yes
      service: name=mysqld state=started enabled=true
    
    
    - name: Update MySQL root password for root account
      sudo: yes
      mysql_user: name=root password={{ db_root_password }} priv=*.*:ALL,GRANT
    
    
    - name: Create .my.cnf file with root password credentials
      sudo: yes
      template: src=.my.cnf.j2 dest=/root/.my.cnf owner=root group=root mode=0600
      notify:
      - restart mysql
    
    
    - name: Create a database
      sudo: yes
      mysql_db: name={{ db_name }}
                collation=utf8_general_ci
                encoding=utf8
                state=present
    
    
    - name: Create a database user
      sudo: yes
      mysql_user: name={{ db_user }}
                  password={{ db_user_password }}
                  priv="{{ db_name }}.*:ALL"
                  host=localhost
                  state=present
    

    Handler:

    ---
    
    - name: restart mysql
      service: name=mysqld state=restarted
    

    .my.cnf.j2:

    [client]
    user=root
    password={{ db_root_password }}
    

提交回复
热议问题