首页 文章

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

提问于
浏览
3

我正在尝试创建一个剧本或角色,让我以ansible by tag开始先前停止的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 回答

  • 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

  • 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
    

    key_nameregion 在我的group_vars / all文件中定义, ec2_id 来自ansible和主机信息, ip_list 在命令行中定义 .

相关问题