2015-12-21 32 views
7

我知道如何使用Ansible創建AWS實例。現在我想要實現的是通過使用創建實例的相同Playbook安裝nginx將該實例配置爲Web服務器。獲取使用Ansible創建的AWS實例的IP地址/屬性

的劇本的目標將是:

  1. 創建一個AWS實例。
  2. 通過設置Nginx服務器將實例配置爲Web服務器。

它是否可能與ansible?

回答

6

閱讀http://www.ansible.com/blog/ansible-ec2-tags它詳細說明了如何創建一個ec2實例(或多個),然後針對它運行任務(即安裝nginx)。

I'f要直接跳到例如劇本https://github.com/chrismeyersfsu/playbook-ec2_properties/blob/master/new_group.yml

  • 造就EC2實例
  • 等待SSH
  • EC2實例Ansible添加動態創建的主機組W /相關EC2 PEM文件(所以你可以ssh到它)
  • 用ping任務調用示例遊戲以顯示一切正常

注:你將與你的任務集合安裝nginx的

@Bidyut 更換ping任務如何

看看Line 27注意使用register: ec2然後在Line 46的EC2參考EC2的IP地址ip地址是「提取」{{ ec2.results[item.0]['instances'][0]['public_ip'] }}。請注意,該示例在循環中調用register。如果您只是創建一個ec2實例,那麼ec2 ip地址引用看起來像{{ ec2.results['instances'][0]['public_ip'] }}

+0

您能否解釋如何從Ansible操作手冊中的AWS返回的JSON結果獲取/獲取特定字段。我試圖谷歌它,但我沒有找到任何。 – Bidyut

+0

該行的'item'是什麼? – Bidyut

+0

在'public_ip'中它的值是None – Bidyut

0

是的,您可以使用單個劇本來啓動實例並安裝nginx。使用安全模塊add_host添加剛剛啓動的實例的IP。然後爲新主機寫劇本。

  1. 啓動使用EC2模塊和註冊實例
  2. 使用add_host模塊的新實例添加到主機庫存的EC2實例
  3. 寫新戲與主機作爲剛剛註冊主機並致電apt安裝nginx

試試吧,如果你需要代碼片段,請告訴我。

+0

我目前正在探索Ansible。從AWS返回給Ansible的JSON輸出中檢索任何特定字段時,我面臨問題。我需要一些解釋說明如何從JSON結果中獲得特定的字段以及如何訪問結果集。 – Bidyut

+0

我可以得到代碼片段嗎?我想通過你的代碼片段。 – Bidyut

2

這是一個可以幫助你的工作示例。

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