使用ansible playbook运行EC2实例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用ansible playbook运行EC2实例相关的知识,希望对你有一定的参考价值。

我想只运行EC2实例。下面的剧本引发了以下错误:

fatal: [localhost]: FAILED! => {"msg": "Unexpected failure during module execution."}

这是环境中的错误吗?

这是剧本。

---
- hosts: localhost
  connection: local
  gather_facts: false

  vars:
      region: us-west-1
  tasks:
    - name: Gathers facts (instance metadata) about remote hosts remote ec2 (all)
      ec2_instance_facts:
       region: "{{ region }}"
       filters:
          "tag:Name": "Security-VPC*"

      register: ec2_metadata
    - name: print ec2 facts of TEST TEST
      debug:
        msg: "{{ ec2_metadata.instances | selectattr('state','equalto','running') | list  }}"
答案

你应该像收集标签一样收集ec2实例事实时过滤状态,并且当将事实传递给debug时,你必须遍历ec2_metadata.instances

这给了我这个适用的例子。

---
- name: test aws ec2
  hosts: localhost
  connection: local
  gather_facts: False

  vars:
    region: us-west-1
  tasks:

    - name: Gathers facts (instance metadata) about remote hosts remote ec2 (all)
      ec2_instance_facts:
        region: "{{ region }}"
        filters:
          "tag:Name": "Security-VPC*"
          instance-state-name: running
      register: ec2_metadata

    - debug:
        msg: "{{ item }}"
      with_items: "{{ ec2_metadata.instances }}"
...

我得到这个输出(显然我的服务器与你的过滤器不匹配)

$ ansible-playbook ec2_instance_facts.yml 

PLAY [test aws ec2] ****************************************************************************************************************************

TASK [Gathers facts (instance metadata) about remote hosts remote ec2 (all)] **************************************************
ok: [localhost]

TASK [debug] ***************************************************

PLAY RECAP ***************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0   

以上是关于使用ansible playbook运行EC2实例的主要内容,如果未能解决你的问题,请参考以下文章

将 Terraform 变量中的数字传递给 Ansible Playbook

使用 Ansible playbook 在 AWS (Amazon) ec2 中部署 Play Framework 应用程序

ansible自动化运维详解ansible中playbook的编写使用执行命令及实例演示

ansible自动化运维详解ansible中playbook的编写使用执行命令及实例演示

ansible自动化运维详解ansible中playbook的编写使用执行命令及实例演示

Ansible:将正在运行的 EC2 实例添加到 Auto-scaling 组