如何从 json 文件动态填充 ansible 角色的参数?

How to populate parameters for an ansible role dynamically from a json file?

我正在努力通过从 JSON 文件中读取它们来动态地将 parameters/vars 传递给 ansible 角色。

考虑以下角色调用(带有可选参数,如 phone、地址、电子邮件、城市)

- name: Ansible role | Create
  include_role:
    name: ansible-role-create-user
  vars:
    persons:
    - name: "john"
      phone:
      - name: "home"
        number: 9999
      - name: "mobile"
        number: "9898"
- name: Ansible role | Create
  include_role:
    name: ansible-role-create-user
  vars:
    persons:
    - name: "Doe"
      email: "johndoe@home.com"
      city: "Skyland"

上述代码是调用角色的两种变体。使用其可选参数,我正在尝试从 JSON 读取该数据并将其提供给角色

JSON 例如: 通话 1:

{
  "name": "John",
  "phone": 
  {
    {"name": "home",   number: "9999"},
    {"name": "mobile",   number: "9898"}
  }  
}

呼叫 2:

{
  "name": "Doe",
  "email": "johndoe@home.com",
  "city": "skyland"
}

如前所述,我想读取示例 JSON 文件并将它们作为参数动态传递给角色。已尝试将文件读取到寄存器并将 var 发送到角色的方法,但我面临

的错误

{ "msg" "'unicode object' 没有属性 'name'"}

我发送方式的示例

- name: cat json to file
  shell: cat jsonfile.json
  register: register_with_json
- name: Ansible role | Create
  include_role:
    name: ansible-role-create-user
  vars: "{{ register_with_json.stdout | from_json }}"

还有更多选择。例如,使用 include_vars。角色和文件

shell> cat roles/ar_create_user/tasks/main.yml
- debug:
    var: persons
shell> cat call1.yml 
persons:
  - name: "john"
    phone:
      - name: "home"
        number: 9999
      - name: "mobile"
        number: "9898"

shell> cat call2.yml 
persons:
  - name: "Doe"
    email: "johndoe@home.com"
    city: "Skyland"

使用剧本

shell> cat playbook.yml
- hosts: localhost
  tasks:

    - include_vars: call1.yml
    - name: Ansible role | Create
      include_role:
        name: ar_create_user

    - include_vars: call2.yml
    - name: Ansible role | Create
      include_role:
        name: ar_create_user

给出(删节)

shell> ansible-playbook playbook.yml

ok: [localhost] => 
  persons:
  - name: john
    phone:
    - name: home
      number: 9999
    - name: mobile
      number: '9898'

ok: [localhost] => 
  persons:
  - city: Skyland
    email: johndoe@home.com
    name: Doe

Q: "I need to get the var(persons) from JSON."

答:下面 JSON 中的文件给出相同的结果

shell> cat call1.yml
{"persons": [
   {"name": "john",
    "phone": [
      {"name": "home",
       "number": 9999},
      {"name": "mobile",
       "number": "9898"}]
       }]
    }

shell> cat call2.yml
{"persons": [
   {"name": "Doe",
    "email": "johndoe@home.com",
    "city": "Skyland"}]
    }