在Ansible中,你可以在YAML文件(通常称为playbook)中使用
hosts
关键字来指定要运行任务的主机。如果你想指定多个主机,可以使用逗号分隔它们,或者使用列表的形式。
以下是一些指定主机的例子:
单个主机
:
“`yaml
hosts: myhost
tasks:
– name: Ensure nginx is at the latest version
apt: name=nginx state=latest
”`
多个主机
:
“`yaml
hosts: host1,host2,host3
tasks:
– name: Ensure nginx is at the latest version
apt: name=nginx state=latest
”`
使用列表指定多个主机
:
“`yaml
hosts:
host1
host2
host3
tasks:
– name: Ensure nginx is at the latest version
apt: name=nginx state=latest
”`
使用通配符
:
“`yaml
hosts: web* # 匹配所有以web开头的主机
tasks:
– name: Ensure nginx is at the latest version
apt: name=nginx state=latest
”`
使用组
:
“`yaml
hosts: webservers
tasks:
– name: Ensure nginx is at the latest version
apt: name=nginx state=latest
”
在这个例子中,
webservers`是一个在Ansible的inventory文件中定义的主机组。
使用变量
:
“`yaml
hosts: “{{ my_hosts }}”
vars:
my_hosts: [“host1”, “host2”, “host3”]
tasks:
– name: Ensure nginx is at the latest version
apt: name=nginx state=latest
”`
确保你的inventory文件(通常是
/etc/ansible/hosts
或者一个自定义的inventory文件)中包含了你想要指定的主机名或者组名。