Ansible with_subelements(列表)

我正在尝试使用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}}'"}

任何人都可以帮助我了解问题所在吗?

baiyanhua_2005 回答:Ansible with_subelements(列表)

您的变量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) }}"
,

列表 web_vhosts

的第一项中没有 mysql
  

{“ 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',{'skip_missing': True}) }}"

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

  loop: "{{ web_vhosts | subelements('mysql',skip_missing=True) }}"
本文链接:https://www.f2er.com/3159938.html

大家都在问