Ansible通配符模式匹配失效,如何正确使用通配符?
Ansible主机通配符匹配的正确方式
首先说明报错原因:你写的hosts: *Fedora触发YAML语法错误,因为在YAML中,*开头的内容会被解析为锚点别名引用,但你并没有提前定义对应的锚点&Fedora,所以报错“found undefined alias”。
要在Ansible中使用通配符匹配主机/组,需要让YAML把通配符当作普通字符串传递给Ansible处理,具体有以下几种正确方式:
1. 用引号包裹通配符字符串
如果要匹配所有组名以Fedora结尾的主机组(对应你的database_Fedora组),需要给通配符加引号,避免YAML误解析:
# Hosts: where our play will run and options it will run with hosts: "*Fedora" become: True # gather_facts: False # Vars: variables that will apply to the play, on all target systems vars: motd: "Welcome to Fedora Linux - Ansible Rocks\n" # Tasks: the list of tasks that will be executed within the playbook tasks: - name: Configure a MOTD (message of the day) copy: content: "{{ motd }}" dest: /etc/motd notify: MOTD changed # Handlers: the list of handlers that are executed as a notify key from a task handlers: - name: MOTD changed debug: msg: The MOTD was changed
2. 直接指定完整组名(更明确)
如果目标主机组是确定的database_Fedora,直接写组名更清晰,不需要通配符:
hosts: database_Fedora
其他常用通配符示例
Ansible支持Shell风格的通配符,常见用法包括:
- 匹配包含指定字符串的组:
hosts: "*Fedora*"(匹配所有组名含Fedora的组) - 匹配IP段:
hosts: "192.168.160.*"(匹配该网段下的所有主机) - 匹配多个组:
hosts: "web_*,database_*"(匹配所有以web_或database_开头的组)
内容的提问来源于stack exchange,提问作者Skegg
相关产品推荐
相关产品推荐

