我正在尝试运行一个剧本,该剧本调用一个角色来部署一些 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
我认为我的情况缺少一些东西,但我找不到到底是什么。任何提示或建议都非常受欢迎
正如 @benoit 和 @mdaniel 所说,错误是在我的理解中,条件应该是:
aws_ec2_infos.instances[0].state.name != 'running'
需要解决的一些额外问题:
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"