2

I'm trying to use ansible and docker to take a backup of my MySQL database. This is my ansible-task:

  docker_container:
    name: "{{ mysql_dump_container_name }}"
    image: mysql:8.0.20
    env:
      MYSQL_ROOT_PASSWORD: "{{ mysql_password }}"
      MYSQL_DATABASE: "{{ mysql_database }}"
    ports:
      - "3307:3307"
    volumes:
      - "{{ mysql_backup_dir }}:/backup"
    entrypoint: "mysqldump -u {{ mysql_username }} -p{{ mysql_password }} --host {{ mysql_host }} {{ mysql_database }} > 1.sql "
    detach: yes
    restart_policy: "unless-stopped"
  become: yes

I am getting the following error:

mysqldump: Couldn't find table: ">"

Entrypoint message is:

"entrypoint": [
    "mysqldump -u root -proot --host wl.cs.net TEST > 1.sql"
],

What am I doing wrong?

toydarian
  • 4,246
  • 5
  • 23
  • 35
user1862354
  • 117
  • 11
  • See https://stackoverflow.com/questions/34632959/redirecting-command-output-in-docker for why it cannot work at all when specified in the exec form.... and I still have a doubt it can work at all on an ENTRYPOINT.... – Zeitounator Aug 05 '21 at 19:15

1 Answers1

3

Actually, you don't need to overwrite the entrypoint as the one that is already in the container will run your command. You just need to make sure that the > ends up at the right place. I do that by quoting the command.
You can do this:

  docker_container:
    name: "{{ mysql_dump_container_name }}"
    image: "mysql:8.0.20"
    volumes:
      - "{{ mysql_backup_dir }}:/backup"
    command: "/bin/sh -c 'mysqldump -u {{ mysql_username }} -p{{ mysql_password }} --host {{ mysql_host }} {{ mysql_database }} > /backup/1.sql'"
    detach: false
    cleanup: true
  become: yes

Additional notes:

  • You do not need any port as the container is not listening for anything.
  • You don't need the env, as you aren't creating a database.
  • You probably want to write the dump to a file in /backup.
  • You probably don't want restart_policy: "unless-stopped" as it doesn't make sense to restart a failed backup, as it will probably fail again. (You need to find out why it failed, first)
  • You will probably want detach: false, so ansible will wait for the container to finish and then show failed if the backup failed.
  • You will probably want cleanup: true, so you don't need to clean up containers manually.

Links:

toydarian
  • 4,246
  • 5
  • 23
  • 35