如何构建ansible脚本来创建实例或不创建实例

时间:2015-01-12 21:33:20

标签: ansible ansible-playbook

我有ansible脚本来构建现有服务器实例上的基础结构。我的清单文件指定所有主机,而剧本对我的清单文件中的实例进行操作。

我的问题是:构建新实例的最佳做法是什么?它应该包含在设置环境的脚本中还是分开?我对脚本如何创建实例(例如EC2实例)和接受库存文件感到有些困惑。

1 个答案:

答案 0 :(得分:1)

可能是示例playbook将帮助您,它将为您创建实例,然后在这些创建的实例上一起运行任务/角色,它还将新创建的实例的ip添加到主机文件(假设它位于同一目录中,您运行此剧本的位置):

---
  - name: Provision an EC2 Instance
    hosts: local
    connection: local
    gather_facts: False
    tags: provisioning
    # Necessary Variables for creating/provisioning the EC2 Instance
    vars:
      instance_type: t1.micro
      security_group: test-sg
      image: ami-98aa1cf0
      region: us-east-1
      keypair: ansible
      count: 1

    # Task that will be used to Launch/Create an EC2 Instance
    tasks:

      - name: Create a security group
        local_action: 
          module: ec2_group
          name: "{{ security_group }}"
          description: Security Group for Servers
          region: "{{ region }}"
          rules:
            - proto: tcp
              type: ssh
              from_port: 22
              to_port: 22
              cidr_ip: 0.0.0.0/0
            - proto: tcp
              from_port: 6800
              to_port: 6800
              cidr_ip: 0.0.0.0/0
          rules_egress:
            - proto: all
              type: all
              cidr_ip: 0.0.0.0/0


      - 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

      - name: Add the newly created EC2 instance(s) to the local host group 
        local_action: lineinfile 
                      dest="./hosts" 
                      regexp={{ item.public_ip }} 
                      insertafter="[ec2server]" line={{ item.public_ip }}
        with_items: ec2.instances


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

      - name: Add tag to Instance(s)
        local_action: ec2_tag resource={{ item.id }} region={{ region }} state=present
        with_items: ec2.instances
        args:
          tags:
            Name: test

      - name: SSH to the EC2 Instance(s)
        add_host: hostname={{ item.public_ip }} groupname=ec2server
        with_items: ec2.instances

  - name: Install these things on Newly created EC2 Instance(s)
    hosts: ec2server
    sudo: True 
    remote_user: ubuntu
    gather_facts: True
    # Run these tasks  
    tasks:
      - include: tasks/upgrade.yml

您的主机文件将如下所示:

[local]
localhost

[ec2server]

希望,这会对你有所帮助。感谢

相关问题