Ansible-即使先前发生故障也要发挥作用

时间:2020-08-07 08:44:39

标签: amazon-web-services ansible

我正在构建一个AMI AMI构建器手册。这个想法是:

  • 生成EC2实例
  • 设置
  • 注册AMI
  • 终止EC2实例

无论如何,即使上一步失败,我也想终止EC2实例。

我的剧本目前看起来像(生成的EC2实例以ec2_servers角色动态添加到aws_spawn_ec2组)):

---
- hosts: localhost
  connection: local
  gather_facts: False
  roles:
    - role: aws_spawn_ec2
      vars:
        ec2_host_group: ec2_servers


- hosts: ec2_servers
  roles:
    - role: provision_ec2


- hosts: localhost
  connection: local
  gather_facts: False
  roles:
    - role: aws_ami_register


- hosts: localhost
  connection: local
  gather_facts: False
  roles:
    -role: aws_terminate_ec2

即使上一场比赛失败,我也希望上一场比赛能够继续进行。有(最好是干净的)方法吗?

[编辑] 我尝试@ Z.Liu回答,出现以下错误: ERROR! 'delegate_to' is not a valid attribute for a IncludeRole

然后我尝试了这一点:

        - name: provision ec2
          include_role:
            name: provision_ec2
            apply:
              delegate_to: ec2_servers

但是我现在遇到了这个错误:

TASK [provision ec2 : Check if reboot is required] **********************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The conditional check 'reboot_required.stat.exists' failed. The error was: error while evaluating conditional (reboot_required.stat.exists): 'dict object' has no attribute 'stat'"}

我有Ansible 2.9.10

谢谢

1 个答案:

答案 0 :(得分:1)

  1. 可行方法 您可以利用Ansible delegate_toblock always

delegate_to可以让您在其他主机上运行剧本

always将执行任务,而不考虑先前的任务结果。

- name: update AMI
  hosts: localhost
  tasks:
    - name: spawn new ec2 instance
      include_role:
        name: aws_spawn_ec2
      vars:
        ec2_host_group: ec2_servers

    - name: provision only spaw ec2 succeed
      block:
        - name: provision ec2
          include_role:
            name: provision_ec2
          delegate_to: ec2_servers

        - name: registe aws AMI
          include_role:
            name: aws_ami_register
      always:
        - name: terminate ec2 instance regardless of the ami registration results
          include_role:
            name: aws_terminate_ec2

  1. 您还可以使用打包程序,在AWS中构建AMI更容易。 https://www.packer.io/intro