使用 Ansible 存储 EC2 实例的 IP


我是 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

作为 ec2 模块执行结果的 ec2 变量应包含有关所创建实例的所有必需信息。您可以使用 debug 模块检查此变量的内容,如下例所示:

- debug:
    var: result

其中肯定会有很多信息,包括实例的 IP 和 DNS 名称,您可以在以后的模块执行中使用这些信息。

事实上,ec2 ansible 模块文档中有一个示例,它几乎完全符合您的需求:

- 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的用户在正确的主机上执行即可。

最新更新