Ansible,如何在主机清单中定义列表? [英] Ansible, how to define a list in host inventory?

查看:188
本文介绍了Ansible,如何在主机清单中定义列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个剧本,我想在主机文件中定义一个字符串列表.

I have a playbook and I want to define a list of strings in my hosts file.

这是我的主机文件:

[dashboard]
1.2.3.4 dashboard_domain=test site_domain=['one','two','foo', 'bar'] 

这是我尝试使用列表文档:

---
- hosts: dashboard
  gather_facts: False
  remote_user: ubuntu
  become: yes

  tasks:

    - name: ping
      ping:

    - debug: 
        msg: "Domain: {{dashboard_domain}}"

    - debug: 
        msg: "Site: {{ item }}"
      with_items: "{{site_domain}}"

但是使用ansible-playbook -i hosts ping.yml运行此剧本会导致以下错误:

However running this playbook with ansible-playbook -i hosts ping.yml causes this error:

任务:[调试] ********************************************** **********************
致命的:[1.2.3.4] => with_items需要一个列表或一个集合

TASK: [debug ] ****************************************************************
fatal: [1.2.3.4] => with_items expects a list or a set

这似乎是将已定义的列表从主机文件传输到剧本的问题,因为直接在剧本中定义列表是可行的:

This seems to be an issue of transferring the defined list from the host file to the playbook because defining the list directly in the playbook works:

---
- hosts: dashboard
  gather_facts: False
  remote_user: ubuntu
  become: yes
  vars:
    site_domain: ['one','two','foo', 'bar'] 
  tasks:

    #### APPLY HTTP-AUTH ####
    - name: ping
      ping:

    - debug: 
        msg: "Domain: {{dashboard_domain}}"

    - debug: 
        msg: "Site: {{ item }}"
      with_items: "{{site_domain}}"

推荐答案

只需引用变量值:

[dashboard]
1.2.3.4 dashboard_domain=test site_domain="['one','two','foo', 'bar']"

在使用INI格式的清单文件的情况下,如果Ansible以未加引号的[开头并将其作为字符串传递,则Ansible不会解析变量值.

It seems in case of INI-formatted inventory files, Ansible does not parse the variable value if it starts with an unquoted [ and passes it as a string.

关于您的示例:如果内部确实有空格,我不确定为什么在读取清单文件时不会出现expected key=value错误.

Regarding your example: I'm not sure why you're not getting an expected key=value error on reading the inventory file, if you really have a space inside.

这篇关于Ansible,如何在主机清单中定义列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆