剧本中的 Ansible 变量检查

Ansible variable check in playbook

我在 vars 文件中将数据库配置如下:

project_dbs:
  - { project_db_name: "project1", project_db_user: "user", tenon_db_password: "pass" }
  - { project_db_name: "project2",  project_db_user: "dev", tenon_db_password: "pass2"}
  - { project_db_name: "project3", project_db_user: "{{datadog_mysql_username}}", project_db_password: "{{datadog_mysql_password}}" }

现在在剧本中我有一张支票:

 - name: copy config.json template to server
   tags: provision
   template: src=config.json dest={{ project_root }}/config
   when: item.project_db_name == "project2"
   with_items: project_dbs

但是 when 检查失败。知道如何让它发挥作用吗?

错误消息如下所示:

fatal: [test]: FAILED! => {"failed": true, "msg": "The conditional check 'item.projects_db_name == \"project2\"' failed. The error was: error while evaluating conditional (item.projects_db_name == \"project2\"): 'unicode object' has no attribute 'projects_db_name'\n\nThe error appears to have been in '/var/lib/jenkins/project/ansible/roles/project2/tasks/main.yml': line 28, 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: copy config.json template to server\n ^ here\n"}

您在 with_items 中使用了称为 "bare variables" 的过时语法:

with_items: project_dbs

这样你的 item 就变成了一个值为 project_dbs 的字符串对象并且 Ansible 报告它没有属性 ("'unicode object' has no attribute 'projects_db_name'").

在 Ansible 2.x 中,您应该按以下方式引用变量:

with_items: "{{ project_dbs }}"

也就是说,您的任务没有使用循环中的值。以下将具有相同的效果:

- name: copy config.json template to server
  tags: provision
  template: src=config.json dest={{ project_root }}/config

您可以过滤 project_dbs 的列表,而不是使用 when,它看起来像这样:

- name: "copy config.json template to server"
  tags: provision
  template: src=config.json dest={{ project_root }}/config
  with_items: "{{ project_dbs | selectattr("project_db_name", "project2") }}"