Ansible:如何在剧本中循环多个变量?

时间:2017-09-19 13:34:43

标签: loops amazon-web-services ansible

我试图在所有EC2实例上编写用于实施AWS Cloudwatch状态检查警报的手册。我尝试硬编码3个值(AWS_Name,Instance_ID& Instance_IP - Private),它对我来说非常好。但是,我需要一个解决方案来处理ansible以使用循环来获取所有变量并逐个为每个实例创建Cloudwatch状态检查警报。

- 
hosts: localhost

  tasks:

    - name: Create Alarm
      ec2_metric_alarm:
         state: present
         region: us-east-1
         name: "Status Check Failed - $AWS_Name - $Instance_IP"
         metric: "StatusCheckFailed"
         namespace: "AWS/EC2"
         statistic: "Minimum"
         comparison: ">="
         threshold: 1
         period: 60
         evaluation_periods: 2
         description: "This will alarm when the instance status check fails"
         dimensions: {'InstanceId': '$Instance_ID'}
         alarm_actions: ["arn:aws:sns:us-east-1:XXXXXXXXXXXX:Cloudwatch-Notifications"]

假设我有两个AWS实例,我可以使用AWS CLI查询或手动获取上面提到的三个变量。现在,我想只运行一次playbook来为所有2个实例创建警报。

找到样本变量

  var1:
    AWS_Name: NAME1
    Instance_ID: i-01b8e4534wt811af4
    Instance_IP: "10.75.169.21"
  var2:
    AWS_Name: NAME2
    Instance_ID: i-4566eftuiw93045
    Instance_IP: "10.75.169.16"

有人,请帮助我。

1 个答案:

答案 0 :(得分:0)

而不是为hosts: localhost运行任务,而是将hosts: all_ec2_hostsdelegate任务运行到localhost。因此,您可以在ec2_metric_alarm中使用目标主机的变量,而不必在循环中运行任务:hosts: all_ec2_hosts会将任务分散到所有主机。

...
hosts: all_ec2_hosts
become: no
tasks:
  - name: Create Alarm
    delegate_to: localhost
    ec2_metric_alarm:
     name: "Status Check Failed - {{ inventory_hostname }}"
     state: present
     region: us-east-1
     ...
     dimensions: "{'InstanceId': '{{ ec2_id }}' }"

显然,您将all_ec2_hosts替换为目标主机或主机组的列表。

ec2_id是EC2动态库存脚本返回的变量,包含EC2实例ID。