[英]Ansible variable check in playbook
I have in the vars file the databases configured as the following:我在 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}}" }
Now in a playbook I have a check:现在在剧本中我有一张支票:
- 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
But the when check is failing.但是 when 检查失败。 Any idea how to make that work?知道如何使它起作用吗?
The error message looks like this:错误消息如下所示:
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"} => {"failed": true, "msg": "条件检查 'item.projects_db_name == \\"project2\\"' 失败。错误是:评估条件时出错 (item.projects_db_name == \\"project2\\" ): 'unicode object' 没有属性 'projects_db_name'\\n\\n错误似乎在 '/var/lib/jenkins/project/ansible/roles/project2/tasks/main.yml': line 28, column 3 ,但可能\\n位于文件中的其他地方,具体取决于确切的语法问题。\\n\\n有问题的行似乎是:\\n\\n\\n- name: copy config.json template to server\\n ^ here\\n"}
You use an outdated syntax called "bare variables" in with_items
:您在with_items
使用了一种称为“裸变量”的过时语法:
with_items: project_dbs
This way your item
becomes a string object with the value of project_dbs
and Ansible reports it doesn't have the attribute ("'unicode object' has no attribute 'projects_db_name'").通过这种方式,您的item
成为具有project_dbs
值的字符串对象,并且 Ansible 报告它没有该属性(“'unicode object' 没有属性 'projects_db_name'”)。
In Ansible 2.x you should quote variables in the following way:在 Ansible 2.x 中,您应该按以下方式引用变量:
with_items: "{{ project_dbs }}"
That said, your task makes no use of the values from the loop.也就是说,您的任务不使用循环中的值。 The following will have the same effect:以下将具有相同的效果:
- name: copy config.json template to server
tags: provision
template: src=config.json dest={{ project_root }}/config
Instead of using when
you could just filter the list of project_dbs so it looks like this:而不是使用when
你可以只过滤 project_dbs 的列表,所以它看起来像这样:
- 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") }}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.