通过带有ansible的标记启动先前停止的EC2实例

时间:2015-02-06 15:55:54

标签: amazon-ec2 ansible

我正在尝试创建一个剧本或角色,让我以ansible by标签开始先前停止的EC2实例(EC2实例通过标签分配给库存中的静态组)。 ec2.ini文件已更改为还返回有关已停止实例的信息。到目前为止,我见过的唯一类似示例依赖于ec2_facts来获取instance_ids

ansible网站上的官方example假设regioninstance_ids已提前知道/已经硬编码。


- name: Start sandbox instances
  hosts: localhost
  gather_facts: false
  connection: local
  vars:
    instance_ids:
      - 'i-xxxxxx'
      - 'i-xxxxxx'
      - 'i-xxxxxx'
    region: us-east-1
  tasks:
    - name: Start the sandbox instances
      ec2:
        instance_ids: '{{ instance_ids }}'
        region: '{{ region }}'
        state: running
        wait: True
        vpc_subnet_id: subnet-29e63245
        assign_public_ip: yes
  role:
    - do_neat_stuff
    - do_more_neat_stuff

最好是我正在寻找一个解决方案,我可以从动态库存中获取必要的变量,例如,如果可能的话。

2 个答案:

答案 0 :(得分:3)

现有的EC2实例可以通过以下播放启动,无需硬编码实例标识符或EC2区域。


--- ec2.yml
- hosts: aws
  gather_facts: false
  tasks:
  - name: start EC2 instance
    local_action:
      module: ec2
        state=running
        region={{ hostvars[inventory_hostname]['ec2_region'] }}
        instance_ids={{ hostvars[inventory_hostname]['ec2_id'] }}
    tags:
      - start-instance

假设标记了动态实例,则以下命令将启动实例:

$ ansible-playbook -i inventory --limit [instance static group name] --tags start-instance ec2.yml

答案 1 :(得分:0)

首先,您必须告诉动态库存脚本返回已关闭的主机。在 ec2.ini 文件中设置为“False”。将其更改为“True”:

# By default, only EC2 instances in the 'running' state are returned. Set
# 'all_instances' to True to return all instances regardless of state.
all_instances = True

这是我使用的剧本:

---
- hosts: "{{ ip_list | default( 'ec2' ) }}"
  connection: ssh
  gather_facts: false
  tasks:
  - name: Start instance
    ec2:
      state: running
      instance_id: "{{ ec2_id }}"
      key_name: "{{ key_name }}"
      region: "{{ region }}"
      wait: true
    delegate_to: localhost
我的group_vars / all文件中定义了 key_name 区域 ec2_id 来自主机信息的ansible,以及 ip_list 在命令行中定义。