如何使用Ansible在RHEL7上设置MySQL8初始root密码并解决报错
问题根因
你遇到的报错本质是shell层语法解析错误,原因是原始Playbook中shell模块的字符串转义、变量引用的引号嵌套逻辑混乱,最终渲染生成的shell命令存在多余转义符、引号错位问题,导致shell解析到(时触发语法错误。
解决方案
方案1:修正shell模块写法
使用Ansible的折叠块语法(>)避免转义地狱,同时补全root用户的host限定,调整后配置如下:
- name: 从安装日志提取临时root密码 shell: cat /var/log/mysqld.log | grep "temporary password" | grep -oE '[^ ]+$' register: tmp_root_password # 新增校验,未提取到密码直接失败避免后续报错 failed_when: tmp_root_password.stdout | length == 0 - name: 通过临时密码修改root密码 shell: > mysql -e "ALTER USER root@localhost IDENTIFIED BY '{{ mysql_root_password }}';" --connect-expired-password -uroot -p"{{ tmp_root_password.stdout }}"
方案2:使用官方mysql_user模块(更推荐)
shell写法存在密码泄露到进程列表的风险,官方模块更安全可靠,正确配置如下:
前置依赖
先确保目标节点安装了MySQL Python依赖,CentOS/RHEL系配置如下:
- name: 安装MySQL Python依赖 yum: name: python3-PyMySQL state: present
Ubuntu/Debian系对应替换包名为python3-pymysql即可。
完整密码修改配置
- name: 从安装日志提取临时root密码 shell: cat /var/log/mysqld.log | grep "temporary password" | grep -oE '[^ ]+$' register: tmp_root_password failed_when: tmp_root_password.stdout | length == 0 - name: 修改root本地登录密码 community.mysql.mysql_user: name: root host: localhost password: "{{ mysql_root_password }}" login_user: root login_password: "{{ tmp_root_password.stdout }}" check_implicit_admin: yes
常见额外注意事项
- 如果使用MySQL 8.0+版本,新密码需要符合默认密码复杂度要求,否则会触发密码校验失败,可提前调整
validate_password相关参数或使用符合长度、字符组合要求的密码。 - 密码修改完成后建议配置本地登录凭证,避免后续操作MySQL重复传递密码:
- name: 配置root用户本地MySQL登录凭证 copy: dest: /root/.my.cnf mode: '0600' content: | [client] user=root password={{ mysql_root_password }}
内容的提问来源于stack exchange,提问作者János
相关产品推荐
相关产品推荐

