获取使用Ansible创建的AWS实例的IP地址/属性

时间:2015-12-21 11:32:11

标签: amazon-web-services ansible ansible-playbook

我知道如何使用Ansible创建AWS实例。现在我想要实现的是通过使用创建实例的相同playbook安装nginx来将该实例配置为Web服务器。

剧本的目标是:

  1. 创建AWS实例。
  2. 通过设置Nginx服务器将实例配置为Web服务器。
  3. 是否可以使用ansible?

3 个答案:

答案 0 :(得分:7)

阅读http://www.ansible.com/blog/ansible-ec2-tags它详细说明了如何启动ec2实例(或多个)然后针对它运行任务(即安装nginx)。

我想直接跳到示例剧本https://github.com/chrismeyersfsu/playbook-ec2_properties/blob/master/new_group.yml

  • 启动ec2实例
  • 等待ssh
  • 将ec2实例添加到Ansible动态创建的主机组w /关联的ec2 pem文件(所以你可以ssh到它)
  • 使用ping任务调用示例播放以显示一切正常

注意:您将使用您的任务集替换ping任务以安装nginx

@Bidyut 如何参考ec2 ip地址

查看Line 27注意register: ec2的使用然后在Line 46,ec2 ip地址被提取出来" {{ ec2.results[item.0]['instances'][0]['public_ip'] }}。请注意,该示例在循环内调用register。如果您只是创建一个ec2实例,那么ec2 ip地址引用将类似于{{ ec2.results['instances'][0]['public_ip'] }}

答案 1 :(得分:3)

这是一个可以帮助您的工作示例。

---
- hosts: localhost
  connection: local
  gather_facts: no
  tasks:
    - name: Create the EC2 Instance
      ec2:
        region: us-east-1
        group: sg-xxxxx # Replace your Security Group here
        keypair: test-key # Replace Key here
        instance_type: t2.mirco
        image: ami-xxxxx # Replace AMI here
        vpc_subnet_id: subnet-xxxxx # Replace Subnet here
        assign_public_ip: yes
        wait: yes
        wait_timeout: 600
        instance_tags:
           Name: "My-EC2-Instance"
      register: ec2

    - name: Create SSH Group to login dynamically to EC2 Instance
      add_host: 
        hostname: "{{ item.public_ip }}"
        groupname: ec2_server
      with_items: ec2.instances

    - name: Wait for SSH to come up
      wait_for: 
        host: "{{ item.public_ip }}" 
        port: 22 
        state: started
      with_items: ec2.instances

 - hosts: ec2_server
   become: yes
   # Use ec2_user if you are using CentOS/Amazon server
   remote_user: ubuntu # for Ubuntu server
   gather_facts: yes
   roles:
     - webserver

答案 2 :(得分:0)

是的,您可以使用单个playbook来启动实例并安装nginx。使用ansible模块 add_host 添加刚刚启动的实例的ip。然后为新主持人写一个游戏。

  1. 使用 ec2 模块启动EC2实例并注册实例
  2. 使用 add_host 模块将新实例添加到主机广告资源
  3. 使用主机作为刚刚注册的主机编写新游戏,并调用 apt 来安装nginx
  4. 尝试一下,如果您需要代码段,请与我们联系。

相关问题