在我的本地硬件上,我有一个运行 Ubuntu 20 的 Vagrant 盒子,我在上面使用 Ansible 2.12.2
我能够访问 AWS,甚至可以在 VPN 中创建 EC2 实例。
当我查看库存时,我可以将 EC2 服务器视为:
"ec2-64-135-69-12.us-west-1.compute.amazonaws.com": {
...,
"tags": {
"Details": "File server and api",
"Name": "File server via Ansible",
"OS": "Ubuntu20",
"Type": "Image Server",
"class": "classfileserver2022"
},
...
},
在我的下一个剧本中,我可以通过以下方式访问服务器
hosts: "ec2-64-135-69-12.us-west-1.compute.amazonaws.com"
但我更愿意通过上面 json 中的任何标签来访问它。
我努力了
hosts: "tags_class_classfileserver2022"
和
hosts:
- tags:Class="classfileserver2022"
但我收到类似的错误
[WARNING]: Could not match supplied host pattern, ignoring: tags_class_classfileserver2022
skipping: no hosts matched
如何使用类别标签访问 EC2 主机? (或任何其他标签..)
我的剧本如下:
---
- name: "Prepare base of {{ server_name }} box"
vars_files:
- vars/0000_vars.yml
- vars/vars_for_base_provision.yml
- vars/vars_for_geerling.security.yml
# hosts: "ec2-54-153-39-10.us-west-1.compute.amazonaws.com" <-- this works
hosts: "tags_Class_{{ tag_class }}"
remote_user: ubuntu
become: yes
gather_facts: no
pre_tasks:
- name: Check for single host
fail: msg="Single host check failed. Try --limit or change `hosts` above."
when: "{{ ansible_play_batch|length }} != 1"
roles:
- { role: geerlingguy.security }
答案1
考虑阅读“库存插件”部分可靠的文档。
要开始使用具有 YAML 配置源的清单插件,请创建一个文件,其中包含为相关插件记录的可接受的文件名架构,然后添加插件:plugin_name。如果插件位于集合中,请使用完全限定名称。
# demo.aws_ec2.yml
plugin: amazon.aws.aws_ec2
[...] 您可以使用带有构造的 keyed_groups 选项的主机变量来创建动态组。选项组还可用于创建组并组合创建和修改主机变量。以下是利用构造特征的 aws_ec2 示例:
# demo.aws_ec2.yml
plugin: amazon.aws.aws_ec2
regions:
- us-east-1
- us-east-2
keyed_groups:
# add hosts to tag_Name_value groups for each aws_ec2 host's tags.Name variable
- key: tags.Name
prefix: tag_Name_
separator: ""
groups:
# add hosts to the group development if any of the dictionary's keys or values is the word 'devel'
development: "'devel' in (tags|list)"
compose:
# set the ansible_host variable to connect with the private IP address without changing the hostname
ansible_host: private_ip_address
[...]您可以使用
ansible-doc -t inventory -l
查看可用插件的列表。用于ansible-doc -t inventory <plugin name>
查看特定于插件的文档和示例。
答案2
根据 Panki 的回答,这就是为我解决的问题
# demo.aws_ec2.yml
inventory-plugins
plugin: amazon.aws.aws_ec2
regions:
- us-west-1
keyed_groups:
- key: tags.class # <-- note: lowercase c
prefix: tags_Class_
separator: ""
示例 playbook 匹配标签: class: uniqueclassname
# example_playbook.yml
---
- name: "Playbook for {{ server_name }} EC2 instance"
vars_files:
- vars/0000_vars.yml
hosts: "tags_Class_{{ tag_class }}"
remote_user: ubuntu
become: yes
gather_facts: no
roles:
- { role: xxxxxxx }
与剧本一起创建的变量:
# vars/0000_vars.yml
tag_class: "uniqueclassname"
server_name: "My Fancy Server"