使用环境变量执行MySQL init命令来创建数据库

时间:2018-05-18 01:42:57

标签: mysql kubernetes

我正在尝试创建一个数据库,如果它不存在并设置了权限,但我无法让它工作,我不断得到You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci' at line 1

我已经包含了尝试执行命令的各种方法

YAML:

  initContainers:
  - name: database-setup
    image: mysql:5.7
    imagePullPolicy: IfNotPresent
    # command:  ["rm", "-fr", "/var/lib/mysql/lost+found"]
    # SQL Syntax error:
    command: [sh,-c,mysql -h mysql-service -p$MYSQL_ROOT_PASSWORD -e "CREATE DATABASE IF NOT EXISTS `$WORDPRESS_DB_NAME` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; GRANT ALL PRIVILEGES ON $WORDPRESS_DB_NAME.* TO '$WORDPRESS_DB_USER'@'%' IDENTIFIED BY '$WORDPRESS_DB_PASSWORD'; FLUSH PRIVILEGES;"]

      # Enviroment Variables arn't passed into mysql shell:
      # - sh
      # - -c
      # - mysql -h mysql-service -p$MYSQL_ROT_PASSWORD
      # - CREATE DATABASE IF NOT EXISTS $WORDPRESS_DB_NAME DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
      # - GRANT ALL PRIVILEGES ON $WORDPRESS_DB_NAME.* TO '$WORDPRESS_DB_USER'@'%' IDENTIFIED BY '$WORDPRESS_DB_PASSWORD';
      # - FLUSH PRIVILEGES;
      # - EXIT;

      # SQL Syntax error:
      # - sh
      # - -c
      # - mysql -h mysql-service -p$MYSQL_ROOT_PASSWORD -e "CREATE DATABASE IF NOT EXISTS `$WORDPRESS_DB_NAME` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; GRANT ALL PRIVILEGES ON $WORDPRESS_DB_NAME.* TO '$WORDPRESS_DB_USER'@'%' IDENTIFIED BY '$WORDPRESS_DB_PASSWORD'; FLUSH PRIVILEGES;

    env:
    - name: WORDPRESS_DB_NAME
      value: wordpress-green
    - name: WORDPRESS_DB_USER
      value: wordpress-green
    - name: WORDPRESS_DB_PASSWORD
      valueFrom:
        secretKeyRef:
          name: wordpress-mysql-pass
          key: wordpress-mysql-pass
    - name: MYSQL_ROOT_PASSWORD
      valueFrom:
        secretKeyRef:
          name: mysql-root-pass
          key: mysql-root-pass

1 个答案:

答案 0 :(得分:0)

尝试为MySQL行执行echo调试变量 返回:

mysql -h mysql-service -p\\REDACTED\\ -e CREATE DATABASE IF NOT EXISTS DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; GRANT ALL PRIVILEGES ON wordpress-green.* TO 'wordpress-green'@'%' IDENTIFIED BY '\\REDACTED\\'; FLUSH PRIVILEGES;

我修复了$ WORDPRESS_DB_NAME未被传递给create DB sting,方法是删除`` - 这会再次导致SQL语法错误,因为它不喜欢数据库名称中的破折号。 相反,我只使用camelCase作为数据库名称

感谢@Tim Biegeleisen的帮助