每个数据库名称一次Ansible运行任务 [英] Ansible run task once per database-name
问题描述
我正在使用ansible将多个站点部署到同一台服务器上.每个站点都是hosts
库存中单独的主机",效果很好.
I'm using ansible to deploy several sites to the same server. Each site is a separate 'host' in the ansible hosts
inventory, which works really well.
但是,只有两个数据库:生产和测试. 如何确保我的数据库迁移任务每个数据库仅运行一次?
However, there are only two databases: production and testing. How can I make sure my database-migration task only runs once per database?
我已经阅读了group_by
,run_once
和delegate_to
功能,但是我不确定如何将它们组合在一起.
I've read into the group_by
, run_once
and delegate_to
features, but I'm not sure how to combine those.
主机看起来像:
[production]
site1.example.com ansible_ssh_host=webserver.example.com
site2.example.com ansible_ssh_host=webserver.example.com
[beta]
beta-site1.example.com ansible_ssh_host=webserver.example.com
beta-site2.example.com ansible_ssh_host=webserver.example.com
[all:children]
production
beta
当前的剧本看起来像这样:
The current playbook looks like this:
---
- hosts: all
- tasks:
# ...
- name: "postgres: Create PostgreSQL database"
sudo: yes
sudo_user: postgres
postgresql_db: db="{{ DATABASES.default.NAME }}" state=present template=template0 encoding='UTF-8' lc_collate='en_US.UTF-8' lc_ctype='en_US.UTF-8'
tags: postgres
register: createdb
delegate_to: "{{ DATABASES.default.HOST|default(inventory_hostname) }}"
# ...
- name: "django-post: Create Django database tables (migrate)"
django_manage: command=migrate app_path={{ src_dir }} settings={{ item.settings }} virtualenv={{ venv_dir }}
with_items: django_projects
#run_once: true
tags:
- django-post
- django-db
- migrate
推荐答案
我发现的最好方法是将任务的执行限制在组的第一台主机上.因此,您需要将组名和数据库添加到group_vars文件中,例如:
The best way I found was to restrict the execution of a task to the first host of a group. Therefore you need to add the groupname and the databases to a group_vars file like:
group_vars/production
group_vars/production
---
dbtype=production
django_projects:
- name: project_1
settings: ...
- name: project_n
settings: ...
group_vars/beta
group_vars/beta
---
dbtype=beta
django_projects:
- name: project_1
settings: ...
- name: project_n
settings: ...
主机
hosts
[production]
site1.example.com ansible_ssh_host=localhost ansible_connection=local
site2.example.com ansible_ssh_host=localhost ansible_connection=local
[beta]
beta-site1.example.com ansible_ssh_host=localhost ansible_connection=local
beta-site2.example.com ansible_ssh_host=localhost ansible_connection=local
[all:children]
production
beta
并将任务执行限制为与该组匹配的第一台主机:
and limit the task execution to the first host that matches that group:
- name: "django-post: Create Django database tables (migrate)"
django_manage: command=migrate app_path={{ src_dir }} settings={{ item.settings }} virtualenv={{ venv_dir }}
with_items: django_projects
when: groups[dbtype][0] == inventory_hostname
tags:
- django-post
- django-db
- migrate
这篇关于每个数据库名称一次Ansible运行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!