Ansible run task once per database-name

南笙酒味 提交于 2019-12-05 18:58:52

So, the below will illustrate why I say "once per group" is generally not supported. Naturally, I would love to see a cleaner out-of-the-box way, and do let me know if "once per group" isn't what you're after.

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

[beta:vars]
dbhost=beta-site1.example.com

[production:vars]
dbhost=site1.example.com

[all:children]
production
beta

Example playbook which will do something on the dbhost once per group (the two real groups):

---
- hosts: all
  tasks:
  - name: "do this once per group"
    sudo: yes
    delegate_to: localhost
    debug:
      msg: "do something on {{hostvars[groups[item.key].0]['dbhost']}} for {{item}}"
    register: create_db
    run_once: yes
    with_dict: groups
    when: item.key not in ['all', 'ungrouped']

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

---
dbtype=production
django_projects:
    - name: project_1
      settings: ...
    - name: project_n
      settings: ...

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!