将变量传递给嵌套剧本的 Ansible 最佳实践?

问题描述:

所以我试图围绕 Ansible 构建一个简单的 LEMP 堆栈.我决定使用嵌套剧本,因为我想要在学习的同时尽可能地进行划分.我遇到了这个问题,我需要传递一些变量,例如 mysql 的 root 密码.现在我想知道是否有任何最佳实践将变量从主剧本传递到各个剧本,还是应该在各个子剧本中设置变量?我使用 这个 repo 作为我自己项目的基础.我还想知道覆盖如何与变量一起使用,如果在子剧本中设置了默认值,在主剧本中设置的变量会覆盖这个值吗?

So I am trying to wrap my head around Ansible and building a simple LEMP stack. I decided to work with a nested playbook because I want to compartmentalize as much as possible, while learning. I run in to this issue where I need to pass some variables such as the root password of mysql. Now I wonder if there is any best practice passing varibles from the main playbook down to the individual plays or should the varibles be set in the individual sub-playbooks? I am using this repo as a basis for my own project. I also wonder how overriding works with varibles, if a default value is set in the sub-playbook does the variables set in the main playbook override this value?

我认为最好的做法是,如果可能的话,重用现有的代码.如果您还没有听说过,Ansible 在 https://galaxy 上有 Galaxy 站点.ansible.com/ 人们在这里共享各种现成的角色.其中一个角色是 mysql(其相关的 github 存储库位于 https://github.com/bennojoy/mysql.)

I imagine best practices is, if possible, to reuse existing code. If you haven't heard about it already, Ansible has Galaxy site at https://galaxy.ansible.com/ where people share various ready-to-use roles. One of such roles is mysql(its relevant github repo is at https://github.com/bennojoy/mysql.)

您不仅可以在您的剧本中利用该角色,而且该页面还提供了展示如何将参数/变量传递给您的角色的示例:

Not only can you utilize that role in your playbooks, but that page also has examples that show how to pass parameters/variables to your roles:

4) 一个完全安装/配置好的 MySQL 服务器,带有主从复制.

4) A fully installed/configured MySQL Server with master and slave replication.

- hosts: master
  roles:
   - {role: mysql, mysql_db: [{name: benz}, {name: benz2}],
                   mysql_users: [{name: ben3, pass: foobar, priv: "*.*:ALL"},
                                 {name: ben2, pass: foo}],
                   mysql_db_id: 8 }

- hosts: slave
  roles:
   - {role: mysql, mysql_db: none, mysql_users: none,
            mysql_repl_role: slave, mysql_repl_master: vm2,
            mysql_db_id: 9, mysql_repl_user: [{name: repl, pass: foobar}] }