Ansible 列表变量未定义

Ansible 列表变量未定义

我有一个剧本,它运行自定义任务来设置 nginx vhost:

  tasks:
    - include: tasks/tweaks.yml

在此剧本中,使用了以下内容var_files

  vars_files:
    - ../config.yml

config.yml有以下包含虚拟主机信息的列表:

nginx_hosts_custom:
  - server_name: "mytest.dev"
    root: /drupal/www/mytest
    is_php: true
    common_config: true
    remote_host: "12.34.56.78"
    remote_root: "/web/ubuntu/www/mytest/public"
    pem: "mytest.pem"

我有以下tweaks.yml内容:

- name: "Extra Nginx hosts for the Drupal sites"
  template:
    src: ../templates/nginx-vhost.conf.j2
    dest: "{{ nginx_vhost_path }}/{{ item.server_name.split(' ')[0] }}.conf"
    force: yes
    owner: root
    group: root
    mode: 0644
  with_items: nginx_hosts_custom
  notify: restart nginx
  when: drupalvm_webserver == 'nginx'

这曾经运行得很好,但现在运行该规定时我收到以下错误:

fatal: [owenvm]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'unicode object' has no attribute 'server_name'\n\nThe error appears to have been in /tasks/tweaks.yml': line 20, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: \"Extra Nginx hosts for the Drupal sites\"\n  ^ here\n"}

因此看起来该变量server_name没有被拾取——有人可以提出解决办法吗?

答案1

中的裸变量with_items,例如with_items: nginx_hosts_custom自 Ansible 2.0 以来已被弃用,并且自 2.2 以来完全不受支持。

你应该使用with_items: "{{ nginx_hosts_custom }}"

答案2

tweaks.yml

- name: "Extra Nginx hosts for the Drupal sites"
  template:
    src: ../templates/nginx-vhost.conf.j2
    dest: "{{ nginx_vhost_path }}/{{ item['server_name'].split(' ') | first }}.conf"
    force: yes
    owner: root
    group: root
    mode: 0644
  with_items: nginx_hosts_custom
  notify: restart nginx
  when: drupalvm_webserver == 'nginx'

此外,模板通常知道要查找的内容../templates(至少在使用角色时)。您确定需要提供相对路径吗?坚持使用模板文件名可能就足够了。

根据 Ansible 版本,with_items可能需要设置为'{{ nginx_host_custom }}'。尽管根据您的错误消息,这不是我们的情况。

我还建议确保nginx_hosts_custom在你的条款中定义when,例如:

when: drupal_webserver == 'nginx' and nginx_hosts_custom is defined and nginx_hosts_custom != False

相关内容