Ansible 委托和 run_once [英] Ansible delegate and run_once

查看:21
本文介绍了Ansible 委托和 run_once的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为本地和开发环境编写了一个特定角色,该角色将从主要用作主数据库的 dbserver 组中的第一台服务器删除并重新创建数据库.

i write one specific roles for local and dev environment that will drop and recreate the database from first server in dbserver group which mostly used as the master database.

group_vars/dbserver

[dbserver]
vagrant1 # master db
vagrant2 # slave db

之后,如果我需要删除数据库并再次创建数据库,基本上我只需要在组中的第一台服务器上运行该命令.

after that, if i need to drop the database and also create the database again, basically i just need that command to be run on the first server in the group.

- name: drop database
  mysql_db: name={{ targetdbname }} state=absent
  when: targetdeploydb == "new"
  delegate_to: "{{ item }}"
  with_items: "{{ groups.dbserver }}"
  run_once: true

- name: create database
  mysql_db: name={{ targetdbname }} state=present
  when: targetdeploydb == "new"
  delegate_to: "{{ item }}"
  with_items: "{{ groups.dbserver }}"
  when: targetdeploydb == "new"
  run_once: true

这是我运行剧本时的日志

Here is the log when i run the playbook

TASK [laravel : drop database] *************************************************
changed: [vagrant1 -> vagrant1] => (item=vagrant1)
changed: [vagrant1 -> vagrant2] => (item=vagrant2)

TASK [laravel : create database] ***********************************************
changed: [vagrant1 -> vagrant1] => (item=vagrant1)
changed: [vagrant1 -> vagrant2] => (item=vagrant2)

我能想到的另一种方法是直接在 delegate_to 上使用主数据库主机名,但这意味着我需要创建另一个变量.另一方面,我认为减少变量的数量并使其更具动态性会更好.请指教

Another way that i can think of is by using the master db hostname directly on delegate_to but it means i need to create another variable. in the other hand, i think it would be better to reduce the number of variable and make it more dynamic. Please advise

推荐答案

如果你只需要将你的任务委派给第一台服务器并且不管当前有多少台服务器都运行一次,请使用:

If you need to delegate your task to the first server only and run it once no matter how many servers in the current play, use:

- name: drop database
  mysql_db: name={{ targetdbname }} state=absent
  when: targetdeploydb == "new"
  delegate_to: "{{ groups['dbserver'] | first }}"
  run_once: true

这篇关于Ansible 委托和 run_once的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆