ansible - 干燥的 Ansible 剧本?
问题描述
我正在尝试使用 ansible 来管理远程 postgres 实例的角色,其剧本如下所示:
---
- hosts: localhost
tasks:
- postgresql_user:
login_host: the.db.com
login_password: password
port: 5432
login_user: admin
db: the-db
name: user-i-want-to-create
这可行,但是我想创建很多这样的用户,并且为每个用户一遍又一遍地重复 5 个参数是乏味且容易出错的。如何将这些变量分解为不需要为每个任务重复它们?
解决方案
This will work pretty easily with a couple of variables and a loop. Something like this should do it:
---
- hosts: localhost
vars:
pgsql_default_db: "the-db"
pgsql_root_user: "admin"
pgsql_root_pass: "password"
pgsql_users:
- name: "user_1"
password: "user_1_password"
- name: "user_2"
password: "user_2_password"
- name: "user_3"
password: "user_3_password"
db: "the-alternate-db"
tasks:
- name: Create database users.
postgresql_user:
login_host: the.db.com
login_password: "{{ pgsql_root_pass }}"
login_user: "{{ pgsql_root_user }}"
port: 5432
db: "{{ item.db | default(pgsql_default_db) }}"
name: "{{ item.name }}"
password: "{{ item.password }}"
with_items: "{{ pgsql_users }}"
This creates three users, defined by the pgsql_users
var, and shows a way to vary some of the properties--user_3
is created with access to a different database than user_1
and user_2
.
There's only one task now, so it's easy to set up, and with a little finagling, the user data could even come from a different source (though the data structure would need to be similar to what I've shown here in order to use the basic with_items
loop).
推荐阅读
- roslyn - 在 .NET 4.8 库项目参考中使用 roslyn
- reactjs - Buildspec.yml 适用于 npm install 但在同一目录中找不到复制的 node_modules
- excel - 如何使用 Excel 中的列名基于值可视化分类数据?
- node.js - Discord bot 在同一个句子中对两个触发器做出两次响应
- mqtt - Mosquitto 坚持作为 MQTT 转发代理
- git - 失败的管道 #xxx 由用户在 2 小时前触发 需要用户验证
- python - 如何在 ElementTree 中获取元素的全名
- amazon-web-services - AWS API Gateway、Lambda 和 AWS 版本控制
- excel - 使用组织帐户凭据从 Excel 中的存储帐户导入 blob/表数据
- html - 为什么我的 CSS 不透明度过渡不起作用?