【问题标题】:Ansible with_subelements (Lists)Ansible with_subelements(列表)
【发布时间】:2019-11-05 11:42:17
【问题描述】:

我正在尝试使用 Ansible 来设置 Apache 虚拟主机和数据库,但并非所有 Vhost 都会有数据库(1 个或更多)。

我已经尝试了很多,也尝试从 here 进行调整,但没有任何效果。我在很长一段时间内做了很多尝试和错误并想出了这个:

我的host_vars(摘录):

web_vhosts:
  - vhost:
      name: domain1.tld
      enabled: true
      serveradmin_email: info@example.org
      https: true
      redirect_to_https: true
      dns_a_record: 1.2.3.4
      update_dns: false
  - vhost:
      name: domain2.tld
      enabled: true
      serveradmin_email: info@example.org
      https: true
      redirect_to_https: true
      dns_a_record: 1.2.3.4
      update_dns: false
      mysql:
        - name: wordpress1
          user: myuser
          password: secret

这是我的距离:

- name: Ensure databases
  mysql_db:
    name: "{{ item.1.name }}"
    state: present
    login_unix_socket: /var/run/mysqld/mysqld.sock
  when: item.0.mysql is defined
  with_subelements:
    - "{{ web_vhosts }}"
    - "mysql"

哪些错误:

fatal: [examplehost]: FAILED! => {"msg": "could not find 'mysql' key in iterated item '{'vhost': {'name': 'domain1.tld', 'enabled': True, 'serveradmin_email': 'info@example.org', 'https': True, 'redirect_to_https': True, 'dns_a_record': '1.2.3.4', 'update_dns': False}}'"}

谁能帮我理解问题所在?

【问题讨论】:

    标签: ansible


    【解决方案1】:

    您的变量web_vhosts 是一个由字典组成的列表,其中第一个元素是vhost。您需要找到子元素vhost.mysql 而不是mysql。这应该可以解决您的问题:

    - name: Ensure databases
      mysql_db:
        name: "{{ item.1.name }}"
        state: present
        login_unix_socket: /var/run/mysqld/mysqld.sock
      loop: "{{ web_vhosts | subelements('vhost.mysql', skip_missing=True) }}"
    

    【讨论】:

    • 哇完美。谢谢!
    【解决方案2】:

    列表的第一项没有mysqlweb_vhosts

    {"msg": "在迭代项 '{'vhost': {'name': domain1.tld' 中找不到 'mysql' 键...

    设置{'skip_missing': True}。例如

    - name: Ensure databases
      mysql_db:
        name: "{{ item.1.name }}"
        state: present
        login_unix_socket: /var/run/mysqld/mysqld.sock
      loop: "{{ lookup('subelements', web_vhosts, 'mysql', {'skip_missing': True}) }}"
    

    先测试循环可能是个好主意

    - name: Debug
      debug:
        var: item
      loop: "{{ lookup('subelements', web_vhosts, 'mysql', {'skip_missing': True}) }}"
    

    或者,可以将 子元素 用作filter

      loop: "{{ web_vhosts | subelements('mysql', skip_missing=True) }}"
    

    【讨论】:

    • 谢谢弗拉基米尔。现在我没有收到错误,但也没有创建数据库。我认为没有匹配项:TASK [web : Ensure databases] ***********
    • 不客气。尝试并测试它。我已经更新了答案。
    • 调试不产生输出:TASK [web : Debug] ****************...(空行)
    猜你喜欢
    • 2017-06-14
    • 2018-09-21
    • 2020-06-06
    • 1970-01-01
    • 2018-10-19
    • 2017-10-09
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多