我想使用Ansible在亚马逊AWS上创建一个小型Web应用程序基础结构,并且希望执行所有流程:启动实例、配置服务等,但是我找不到一个合适的工具或模块来处理这些问题。主要是EC2 Launch。
非常感谢。
我想使用Ansible在亚马逊AWS上创建一个小型Web应用程序基础结构,并且希望执行所有流程:启动实例、配置服务等,但是我找不到一个合适的工具或模块来处理这些问题。主要是EC2 Launch。
非常感谢。
这是您问题的简短答案,如果您想要详细和完全自动化的角色,请告诉我。谢谢
先决条件:
Ansible
Python boto库
在环境设置中设置AWS访问密钥和秘密密钥
(最好放在~./boto内)
为了创建EC2实例,请修改您可以在“vars”下的“ec2_launch.yml”文件中找到的这些参数:
count # 要创建的实例数量
一旦您提到了这些参数,请运行以下命令:
ansible-playbook -i hosts ec2_launch.yml
hosts文件的内容:
[local]
localhost
[webserver]
ec2_launch.yml 文件的内容:
---
- 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: webserver # Change the security group name here
image: ami-98aa1cf0 # Change the AMI, from which you want to launch the server
region: us-east-1 # Change the Region
keypair: ansible # Change the keypair name
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 webserver 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: 80
to_port: 80
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 (located inside the directory)
local_action: lineinfile
dest="./hosts"
regexp={{ item.public_ip }}
insertafter="[webserver]" 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: webserver
正如其他人所说,cloud模块包含几乎所有您需要的AWS支持。 也就是说,Ansible的范例最有意义的是有现有的SSH:able机器进行目标和连接。相比之下,实例化阶段基本上要求您将目标定位到本地计算机,然后从那里调用AWS API端点。
像你一样,我希望有一个单独的命令,并且能够从EC2实例化过渡到配置。 有关如何在文档中完成此类操作的建议,但它依赖于add_host模块来调整Ansible对当前主机清单的理解,即使如此,我也找不到一种解决方案,它并不像我正在与系统一起工作而不是反抗系统。
最终,我选择了两个不同的playbook:provision.yml使用ec2、ec2_group、ec2_vol、ec2_eip和route53模块确保我拥有硬件设施,然后configure.yml更像是传统的Ansible site.yml,它能够将主机清单(在我的情况下是静态的,但动态的也可以很好地工作)视为给定,并执行所有良好的声明性状态转换。
这两个playbook都是幂等的,但是configure.yml是在长期运行中需要重新运行的。
ec2
任务参数保留在单独的group_vars
或host_vars
文件中,因为在ec2
任务针对localhost
运行时还没有主机可供通信。您如何在provision.yml
playbook中解决这个问题? - sscEC2模块是专门用于创建和销毁实例的。
如果您想要“最佳”方法,那么很难超越CloudFormation,可以从Ansible启动它。
local_action
,在什么情况下不使用?我看到过像上面那样的代码片段(例如local_action: ec2 ...
),也看到过直接执行ec2: ...
的代码片段,但我找不到任何关于何时更喜欢其中之一的信息。例如,Ansible文档中的AWS介绍并没有使用它:https://docs.ansible.com/ansible/guide_aws.html - user21037