我是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
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
答案 0 :(得分:2)
作为ec2模块执行结果的ec2
变量应包含有关所创建实例的所有必需信息。您可以使用the debug
module检查此变量的内容,如下例所示:
- debug:
var: result
肯定会有很多信息,包括您的实例的IP和DNS名称,您可以在以后的模块执行中使用它们。
事实上,ec2 ansible module文档中有一个示例几乎完全符合您的需求:
- name: Add new instance to host group
add_host:
hostname: "{{ item.public_ip }}"
groupname: launched
with_items: "{{ ec2.instances }}"
以上代码将所有已创建实例的IP地址添加到当前库存。在您的情况下,您只需将add_host
更改为lineinfile
(或template
)模块:
- 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 }}"
确保实际可以更改/etc/hosts
的用户在正确的主机上执行此任务。