首页 > 解决方案 > 干燥的 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 个参数是乏味且容易出错的。如何将这些变量分解为不需要为每个任务重复它们?

标签: ansibleyaml

解决方案


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).


推荐阅读