在Ansible中,根据用户配置将字典附加到字典列表

huangapple go评论93阅读模式
英文:

Append a dict to a list of dicts in Ansible based on user configuration

问题

以下是您提供的文本的翻译:

我想通过Ansible部署一个应用程序,该应用程序可以通过systemd服务以可配置的应用节点数运行。我有一个管理这些服务的角色,但它需要服务的名称以及优先级等参数。

在我的playbook中,用户定义了类似于以下内容的内容:

  1. application_nodes:
  2. - name: "node1"
  3. api_port: 3900
  4. - name: "node2"
  5. api_port: 3910

因此,我需要追加此systemd角色管理的服务列表。我尝试了以下方式:

  1. service_list: "{% for node in application_nodes %}{'name': 'application_{{ node.name }}.service', 'priority': 1000}{% endfor %}"
  2. devture_systemd_service_manager_services_list_auto: |
  3. {{
  4. ([{{ service_list }}])
  5. }}

这导致了以下错误:

  1. FAILED! => {"msg": "在模板化 '{{\n ([{{ service_list }}])\n}}\n' 时发生了未处理的异常。错误是 <class 'ansible.errors.AnsibleError'>,原始消息是:在模板化字符串时出现模板错误: 预期的标记 ':',得到 '}'。字符串: {{\n ([{{ service_list }}])\n}}。预期的标记 ':',得到 '}'"}

我无法弄清楚我在这里做错了什么。

最终应该像这样工作(自动适用于每个节点):

  1. devture_systemd_service_manager_services_list_auto: |
  2. {{
  3. ([{'name': 'application_node1.service', 'priority': 1000}])
  4. +
  5. ([{'name': 'application_node2.service', 'priority': 1000}])
  6. }}

我还考虑过类似于以下方式:

  1. - name: 追加服务列表以按节点
  2. set_fact:
  3. devture_systemd_service_manager_services_list_auto: "{{ devture_systemd_service_manager_services_list_auto + [{'name': 'application_{{ item.name }}.service', 'priority': 1000, 'groups': ['applicationname']}] }}"
  4. loop: "{{ application_nodes }}"
  5. - name: "打印服务"
  6. debug:
  7. msg: "services {{ devture_systemd_service_manager_services_list_auto }}"

其中错误类似于这个问题,但该解决方案对我来说不起作用,因为我想访问字典的特定键:

  1. TASK [custom/base : Print services B]
  2. fatal: [mydomain]: FAILED! => {"msg": "该任务包含一个未定义变量的选项。错误是:[{'name': 'application_node2.service', 'priority': 1000, 'groups': ['applicationname']}, {'name': 'application_{{ item.name }}.service', 'priority': 1000, 'groups': ['applicationname']}]: 'item' 未定义。'item' 未定义。[{'name': 'application_node2.service', 'priority': 1000, 'groups': ['applicationname']}, {'name': 'application_{{ item.name }}.service', 'priority': 1000, 'groups': ['applicationname']}]: 'item' 未定义。'item' 未定义
  3. 错误似乎出现在文件 '/.../roles/custom/base/tasks/add_services.yml' 中:第11行,第3列,但根据确切的语法问题,它也可能出现在文件的其他位置。
  4. 有问题的行似乎是:
  5. - name: "打印服务 B"
  6. ^ 在这里
  7. "}
英文:

I want to deploy an application via ansible that has a configurable number of application nodes running via a systemd service. I have a role that manages these services for me but expects the name of the services along with e.g. the priority.

In my playbook the user defines something like this

  1. application_nodes:
  2. - name: &quot;node1&quot;
  3. api_port: 3900
  4. - name: &quot;node2&quot;
  5. api_port: 3910

Therefore I need to append the list that this the systemd role manages. I tried the following

  1. service_list: &quot;{% for node in application_nodes %}{&#39;name&#39;: &#39;application_{{ node.name }}.service&#39;, &#39;priority&#39;: 1000}{% endfor %}&quot;
  2. devture_systemd_service_manager_services_list_auto: |
  3. {{
  4. ([{{ service_list }}])
  5. }}

This results in the following error

  1. FAILED! =&gt; {&quot;msg&quot;: &quot;An unhandled exception occurred while templating &#39;{{\n ([{{ service_list }}])\n}}\n&#39;. Error was a &lt;class &#39;ansible.errors.AnsibleError&#39;&gt;, original message: template error while templating string: expected token &#39;:&#39;, got &#39;}&#39;. String: {{\n ([{{ service_list }}])\n}}\n. expected token &#39;:&#39;, got &#39;}&#39;&quot;}

I cannot figure out what I did wrong here.

I the end it should work like this (except automatically for every node)

  1. devture_systemd_service_manager_services_list_auto: |
  2. {{
  3. ([{&#39;name&#39;: &#39;application_node1.service&#39;, &#39;priority&#39;: 1000}])
  4. +
  5. ([{&#39;name&#39;: &#39;application_node2.service&#39;, &#39;priority&#39;: 1000}])
  6. }}

I also considered something like this

  1. - name: Append services list by nodes
  2. set_fact:
  3. devture_systemd_service_manager_services_list_auto: &quot;{{ devture_systemd_service_manager_services_list_auto + [{&#39;name&#39;: &#39;application_{{ item.name }}.service&#39;, &#39;priority&#39;: 1000, &#39;groups&#39;: [&#39;applicationname&#39;]}] }}&quot;
  4. loop: &quot;{{ application_nodes }}&quot;
  5. - name: &quot;Print services&quot;
  6. debug:
  7. msg: &quot;services {{ devture_systemd_service_manager_services_list_auto }}&quot;

Where the error is similar to this issue but the solution does not work for me as I want to access a specific key of the dictionary

  1. TASK [custom/base : Print services B] ********************************************************************************************************************************************************************************************************************
  2. fatal: [mydomain]: FAILED! =&gt; {&quot;msg&quot;: &quot;The task includes an option with an undefined variable. The error was: [{&#39;name&#39;: &#39;application_node2.service&#39;, &#39;priority&#39;: 1000, &#39;groups&#39;: [&#39;applicationname&#39;]}, {&#39;name&#39;: &#39;application_{{ item.name }}.service&#39;, &#39;priority&#39;: 1000, &#39;groups&#39;: [&#39;applicationname&#39;]}]: &#39;item&#39; is undefined. &#39;item&#39; is undefined. [{&#39;name&#39;: &#39;application_node2.service&#39;, &#39;priority&#39;: 1000, &#39;groups&#39;: [&#39;applicationname&#39;]}, {&#39;name&#39;: &#39;application_{{ item.name }}.service&#39;, &#39;priority&#39;: 1000, &#39;groups&#39;: [&#39;applicationname&#39;]}]: &#39;item&#39; is undefined. &#39;item&#39; is undefined\n\nThe error appears to be in &#39;/.../roles/custom/base/tasks/add_services.yml&#39;: line 11, 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: \&quot;Print services B\&quot;\n ^ here\n&quot;}

答案1

得分: 2

首先,你所使用的角色中的变量定义对于一个简单的字典列表来说过于复杂,这会导致混淆。所以,为了明确起见,以下表达式:

  1. devture_systemd_service_manager_services_list_auto: |
  2. {{
  3. ([{&#39;name&#39;: &#39;application_node1.service&#39;, &#39;priority&#39;: 1000}])
  4. +
  5. ([{&#39;name&#39;: &#39;application_node2.service&#39;, &#39;priority&#39;: 1000}])
  6. }}

实际上等同于:

  1. devture_systemd_service_manager_services_list_auto:
  2. - name: application_node1.service
  3. priority: 1000
  4. - name: application_node2.service
  5. priority: 1000

其次,我认为第二个混淆源是你使用了 append 这个术语(在Ansible中是向列表添加更多元素的操作),而不是 combine(即从另一个字典中添加/更新键)。

有了这些澄清,我们可以满足你的需求:

  1. 从原始列表中提取每个元素的 name 属性
  2. 转换该名称以使其与你期望的服务名称匹配
  3. 将包含该名称和期望优先级的字典附加到结果列表的相关键中

请注意,必须转换名称,这使得很难在变量定义的模板中避免循环(在Ansible中我们通常尽量避免这样做)。但这仍然可以在一个表达式中完成,如下面测试剧本所示:

  1. ---
  2. - hosts: localhost
  3. gather_facts: false
  4. vars:
  5. application_nodes:
  6. - name: &quot;node1&quot;
  7. api_port: 3900
  8. - name: &quot;node2&quot;
  9. api_port: 3910
  10. devture_systemd_service_manager_services_list_auto: &gt;-
  11. {%- set result = [] -%}
  12. {%- for node in application_nodes -%}
  13. {%- set service_name = node.name | regex_replace(&#39;^(.*)$&#39;, &#39;application_\.service&#39;) -%}
  14. {{ result.append({&#39;name&#39;: service_name, &#39;priority&#39;: 1000}) }}
  15. {%- endfor -%}
  16. {{ result }}
  17. tasks:
  18. - name: Show our list
  19. ansible.builtin.debug:
  20. var: devture_systemd_service_manager_services_list_auto

这将产生(仅显示相关任务输出):

  1. TASK [Show our list] *********************************************************
  2. ok: [localhost] => {
  3. "devture_systemd_service_manager_services_list_auto": [
  4. {
  5. "name": "application_node1.service",
  6. "priority": 1000
  7. },
  8. {
  9. "name": "application_node2.service",
  10. "priority": 1000
  11. }
  12. ]
  13. }
英文:

To start with, the var definition in the role your are using is overly complicated for something as simple as a list of dicts. This is a source of confusion. So to be clear the following expression:

  1. devture_systemd_service_manager_services_list_auto: |
  2. {{
  3. ([{&#39;name&#39;: &#39;application_node1.service&#39;, &#39;priority&#39;: 1000}])
  4. +
  5. ([{&#39;name&#39;: &#39;application_node2.service&#39;, &#39;priority&#39;: 1000}])
  6. }}

is actually the exact equivalent of:

  1. devture_systemd_service_manager_services_list_auto:
  2. - name: application_node1.service
  3. priority: 1000
  4. - name: application_node2.service
  5. priority: 1000

The second source of confusion IMO is that you used the term append (which is in Ansible the fact to add more elements to a list) rather than combine (i.e. adding/updating keys in one dict from an other dict).

Those precisions being made, we can fulfill your requirement by:

  1. Extracting the name attribute from each element in the original list
  2. Transform that name so that it matches your expected service name
  3. Append a dict containing that name and the expected priority in relevant keys to a result list

Note that having to transform the name makes it difficult to avoid looping inside a template for the var definition (which we generally tend to avoid in Ansible). But this can still be done in one single expression as demonstrated in the following test playbook:

  1. ---
  2. - hosts: localhost
  3. gather_facts: false
  4. vars:
  5. application_nodes:
  6. - name: &quot;node1&quot;
  7. api_port: 3900
  8. - name: &quot;node2&quot;
  9. api_port: 3910
  10. devture_systemd_service_manager_services_list_auto: &gt;-
  11. {%- set result = [] -%}
  12. {%- for node in application_nodes -%}
  13. {%- set service_name = node.name | regex_replace(&#39;^(.*)$&#39;, &#39;application_\.service&#39;) -%}
  14. {{ result.append({&#39;name&#39;: service_name, &#39;priority&#39;: 1000}) }}
  15. {%- endfor -%}
  16. {{ result }}
  17. tasks:
  18. - name: Show our list
  19. ansible.builtin.debug:
  20. var: devture_systemd_service_manager_services_list_auto

which gives (relevant task output only)

  1. TASK [Show our list] *********************************************************
  2. ok: [localhost] =&gt; {
  3. &quot;devture_systemd_service_manager_services_list_auto&quot;: [
  4. {
  5. &quot;name&quot;: &quot;application_node1.service&quot;,
  6. &quot;priority&quot;: 1000
  7. },
  8. {
  9. &quot;name&quot;: &quot;application_node2.service&quot;,
  10. &quot;priority&quot;: 1000
  11. }
  12. ]
  13. }

答案2

得分: 1

  1. - 主机:全部
  2. 变量:
  3. 应用节点:
  4. - 名称:“node1
  5. API端口:3900
  6. - 名称:“node2
  7. API端口:3910
  8. 任务:
  9. - 设置事实:
  10. # 循环前后的方括号使其成为实际列表。
  11. # 为确保列表项与彼此分开,我们必须在每个项后面添加逗号。幸运的是,Ansible / Python 对没有最终项的逗号不太挑剔。;-)
  12. 服务列表: >
  13. [
  14. {% for node in application_nodes %}
  15. {'name': 'application_{{ node.name }}.service', 'priority': 1000},
  16. {% endfor %}
  17. ]
  18. - 设置事实:
  19. devture_systemd_service_manager_services_list_auto: >
  20. {{ devture_systemd_service_manager_services_list_auto|default([]) +
  21. service_list }}
  22. - 调试:
  23. 变量:devture_systemd_service_manager_services_list_auto
英文:

You almost had it in your first try. If you add a few things to your service_list it ends up being a list of dicts -- which is ultimately what you want to append to devture_systemd_service_manager_services_list_auto.

  1. - hosts: all
  2. vars:
  3. application_nodes:
  4. - name: &quot;node1&quot;
  5. api_port: 3900
  6. - name: &quot;node2&quot;
  7. api_port: 3910
  8. tasks:
  9. - set_fact:
  10. # The square brackets before and after the loop make this an actual
  11. # list.
  12. # To make sure that the list items are separated from each other, we
  13. # have to add a comma after each item. Luckily Ansible / Python isn&#39;t
  14. # too picky about a comma without a final item. ;-)
  15. service_list: &gt;
  16. [
  17. {% for node in application_nodes %}
  18. {&#39;name&#39;: &#39;application_{{ node.name }}.service&#39;, &#39;priority&#39;: 1000},
  19. {% endfor %}&quot;
  20. ]
  21. - set_fact:
  22. devture_systemd_service_manager_services_list_auto: &gt;
  23. {{ devture_systemd_service_manager_services_list_auto|default([]) +
  24. service_list }}
  25. - debug:
  26. var: devture_systemd_service_manager_services_list_auto

huangapple
  • 本文由 发表于 2023年2月19日 06:16:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定