Amazon ec2 使用Ansible存储EC2实例的IP
我是Ansible的新手,我写了一本Ansible剧本,它将增加EC2实例。我想保存已创建实例的公共IP或DNS名称,以便对其执行其他操作Amazon ec2 使用Ansible存储EC2实例的IP,amazon-ec2,ansible,Amazon Ec2,Ansible,我是Ansible的新手,我写了一本Ansible剧本,它将增加EC2实例。我想保存已创建实例的公共IP或DNS名称,以便对其执行其他操作 tasks: - name: Create a security group local_action: module: ec2_group name: "{{ security_group }}" description: Security Group for webserver Servers
tasks:
- name: Create a security group
local_action:
module: ec2_group
name: "{{ security_group }}"
description: Security Group for webserver Servers
region: "{{ region }}"
rules:
- proto: tcp
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 80
to_port: 80
cidr_ip: 0.0.0.0/0
rules_egress:
- proto: all
cidr_ip: 0.0.0.0/0
register: basic_firewall
- name: Launch the new EC2 Instance
local_action: ec2
group={{ security_group }}
instance_type={{ instance_type}}
image={{ image }}
wait=true
region={{ region }}
keypair={{ keypair }}
count={{count}}
register: ec2
This playbook runs successfully and creates 1 instance on EC2. But need to save the IP or DNS name to hosts file for future use
作为ec2模块执行结果的
ec2
变量应包含所创建实例的所有必要信息。您可以使用下面示例中的like检查此变量的内容:
- debug:
var: result
其中肯定会有很多信息,包括您实例的IP和DNS名称,您可以在以后的模块执行中使用这些信息
事实上,文档中有一个例子几乎完全符合您的需要:
- name: Add new instance to host group
add_host:
hostname: "{{ item.public_ip }}"
groupname: launched
with_items: "{{ ec2.instances }}"
上面的代码将所有创建实例的IP地址添加到当前资源清册中。在您的情况下,您只需更改添加\u主机
,例如(或)模块:
只需确保此任务由实际可以更改
/etc/hosts
的用户在适当的主机上执行,谢谢。在我的剧本中添加了提到的台词之后,它就起作用了。
- name: Ensure the added instance is in /etc/hosts
lineinfile:
regexp: '^.* created_host'
line: "{{ item.public_ip }} created_host"
state: present
with_items: "{{ ec2.instances }}"