通过 Ansible 分配 EC2

Allocate EC2 through Ansible

通过Ansible创建EC2实例时,如何指定安全组(这是针对非账户默认的Amazon VPC环境)?在我的例子中,我试图为我的网络服务器 EC2 实例分配一个安全组(当前存在),该实例将流量限制为仅来自位于它前面的 ELB 的流量。如果我尝试以下操作:

- name: Create webserver instance
  ec2: 
    key_name: "{{ project_name }}-{{ env }}-key"
    image: "{{ image }}"
    instance_type: "{{ instance_type }}"
    instance_tags: '{"Name":"{{ project_name }}-{{ env }}-{{ webserver_name }}","Owner":"{{ project_name }}", "Type":"{{ webserver_name }}","Environment":"{{ env }}"}'
    region: "{{ aws_region }}"
    group: "{{ security_group_name }}"
    wait: true
  register: ec2

其中 {{ security_group_name }} 是在 AWS 控制台中找到的 'Group Name',我收到以下错误:'Value () for parameter groupId is invalid. The value cannot be empty'

如果我尝试以下操作:

- name: Create webserver instance
  ec2: 
    key_name: "{{ project_name }}-{{ env }}-key"
    image: "{{ image }}"
    instance_type: "{{ instance_type }}"
    instance_tags: '{"Name":"{{ project_name }}-{{ env }}-{{ webserver_name }}","Owner":"{{ project_name }}", "Type":"{{ webserver_name }}","Environment":"{{ env }}"}'
    region: "{{ aws_region }}"
    group_id: "{{ security_group_id }}"
    wait: true
  register: ec2

其中 {{ security_group_id }} 是在 AWS 控制台中找到的 'Group Id'(例如 sg-xxxxxx),我收到相同的错误。 Ansible 文档指出 'group' 和 'group_id' 用于安全组 (http://docs.ansible.com/ansible/ec2_module.html) 的规范。

我唯一能想到的是 AWS 找不到安全组,因为我正在创建它,但它不知道要将其放置在哪个 VPC 中,或者它将它放置在我的默认 VPC 中,但找不到安全组分组,因为它在不同的 VPC 中。

所以,也许更好的问题是,如何为特定的 EC2 实例指定 VPC(当我在一个区域中有多个 VPC 时)?

I receive the following error: 'Value () for parameter groupId is invalid. The value cannot be empty'

听起来这些变量没有定义;你在哪里定义它们?不使用变量,直接把值赋值的时候行吗?

So, maybe a better question is, how to I specify the VPC for a particular EC2 instance (when I have multiple VPCs in a region)?

VPC 由其他值暗示,特别是 group/group_idvpc_subnet_id

使用 group_id 而不是 group 的主要优点之一是,如果您不小心将子网用于错误的 VPC,则会出现错误,而如果您的安全组具有在多个 VPC 中使用相同的名称,使用 group 和不正确的 vpc_subnet_id 将在错误的位置成功启动机器。

无法在您的剧本中指定 VPC ID。相反,您指定 vpc_subnet_id。 AWS 可以根据 subnet id 找出 VPC。您没有指定子网 ID,因此 AWS 假定您要在 EC2 Classic 中启动它。由于在 EC2 Classic 中找不到指定的安全组,您收到 not foundinvalid 错误。

如何解决这个问题?找到您要启动实例的子网的 id。每个 VPC 可以再有一个 public and/or 个私有子网。在 AWS 仪表板中,select VPC Service 将列出子网和 VPC。找到您要启动的子网,并在剧本中指定其 ID。

vpc_subnet_id: subnet-29e63245