mariadbaws-codebuildbuildspec

How can I run a multi line command in a buildspec.yaml for CodeBuild


I need to set up MariaDB on an AWS CodeDeploy instance with local username and password so that my Laravel App can connect to it and complete testing.

This buildspec does most of what I want to achieve:

version: 0.2

phases:
  install:
    runtime-versions:
      php: 8.2
    commands:
        - export DEBIAN_FRONTEND=noninteractive

        #Update
        - apt update -y

        #Start Mysql if you need it
        - apt install mariadb-server -y
        - service mariadb start

        #Install composer
        - php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
        - php composer-setup.php ;
        - php -r "unlink('composer-setup.php');" ;
        - mv composer.phar /usr/local/bin/composer


  build:
    commands:
      - composer install

  post_build:
    commands:
      - php artisan test --recreate-databases

I am struggling to add the user however.

I need to run sudo mariadb

And in the MariaDb prompt that opens then run:

CREATE USER 'ROOT'@'%' IDENTIFIED BY '';
GRANT ALL PRIVILEGES ON *.* TO 'phpmyadmin'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit

But I can't work out how to tell the build spec to run those SQL commands within the mariadb terminal that opens, rather than the outer shell it defaults to. I have tried quotations, new lines, and can't find any hints in the build specification documentation.


Solution

  • I eventually got this working using echo and the pipe operator:

            #Start Mysql if you need it
            - apt install mariadb-server -y
            - service mariadb start
            - echo " CREATE DATABASE \`test\`;
              CREATE USER 'test'@'%' IDENTIFIED BY 'test';
              GRANT ALL PRIVILEGES ON *.* TO 'test'@'%' WITH GRANT OPTION;" | sudo mariadb
    
    

    NB for this project I need privileges to create other users - you will probably want a more restrictive GRANT statement.