检查 EC2 实例是否存在并正在运行,然后跳过部署

问题描述 投票:0回答:2

我正在尝试运行一个剧本,该剧本调用一个角色来部署一些 EC2 实例,一切正常,除了我想在 EC2 实例存在且处于运行状态时设置一个条件以跳过部署我使用以下命令来检索 ec2_infos :

## Check if an instance with same name exist on AWS
- name: Get {{ ec2_name }} infos
  ec2_instance_info:
    region: "us-east-1"
    filters:
      "tag:Name": "{{ ec2_name }}"
      instance-state-name: [ "running"]
  register: ec2_infos

- name: DEBUG
  debug: msg="{{ aws_ec2_infos }}"

在部署阶段我的情况如下:


- name: "{{ ec2_description }} - {{ ec2_name }}"
  cloudformation:
    stack_name: "some name "
    state: "present"
    region: "{{ aws_region }}"
    template: "PATH/ec2.json"
    template_parameters:
      Name: "{{ ec2_name }}"
      Description: "{{ ec2_description }}"
      KeyName: "{{key_name }}"
      KmsKeyId: "{{ key_id }}"
      GroupSet: "{{ id }}"
      IamInstanceProfile: "{{ name }}"
      Type: "OS"
  **when: ec2_infos.state[0].name != 'running'**

但我收到一条错误消息:

"msg": "The conditional check 'aws_ec2_infos.state[0].name != 'running'' failed. The error was: error while evaluating conditional (aws_ec2_infos.state[0].name != 'running'): 'dict object' has no attribute 

我认为我的情况缺少一些东西,但我找不到到底是什么。任何提示或建议都非常受欢迎

amazon-web-services amazon-ec2 ansible
2个回答
1
投票

正如 @benoit 和 @mdaniel 所说,错误是在我的理解中,条件应该是:

aws_ec2_infos.instances[0].state.name != 'running'

0
投票

需要解决的一些额外问题:

  • Ansible 配合 terraform 部署 EC2 实例不是幂等的!它每次都会摧毁并重建你的机器!
  • 机器可能处于除运行之外的有效状态。例如。关闭。源中的完整列表。警告;不保证 AWS 会保持该列表相同。检查来源!
  • 如果机器被破坏并重新创建,主机密钥将会改变。特别感谢上面的帖子提供了解决方案。如果您处于经常重新部署计算机的环境中,则更容易忽略主机密钥检查。
  • 在 terraform 之后,机器需要一些时间来启动。如果部署后没有立即进行连接检查,您的 ansible 脚本将会失败!

playbook.yml

---
- name: Deploy My Server
  hosts: MyServerName
  gather_facts: false

  tasks:

    # Source of instance-state-name values:
    # https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html
    - name: Check existence of server
      ec2_instance_info:
        region: "us-east-1"
        filters:
          "tag:Name": "MyServerName"
          instance-state-name: ['pending','running','shutting-down','stopping',
            'stopped']
      delegate_to: localhost
      register: server_info

    - name: Deploy EC2 machine
      community.general.terraform:
        project_path: terraform_code/
        state: present
      delegate_to: localhost
      when: server_info.instances | length == 0

    - name: Wait 5 minutes, but only start checking after 30 seconds
      ansible.builtin.wait_for_connection:
        delay: 30
        timeout: 300
      when: server_info.instances | length == 0

- name: Reconnect to server with gather_facts
  hosts: MyServerName
  tasks:
    - name: Do stuff...

库存.yml

MyServerName:
  hosts:
    192.168.0.1:
  vars:
    ansible_ssh_common_args:
      "-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
© www.soinside.com 2019 - 2024. All rights reserved.