我在Ansible中有以下实例创建任务:
- name: Provisioning Spot instaces
ec2:
assign_public_ip: no
spot_price: "{{ ondemand4_price }}"
spot_wait_timeout: 300
assign_public_ip: no
aws_access_key: "{{ assumed_role.sts_creds.access_key }}"
aws_secret_key: "{{ assumed_role.sts_creds.secret_key }}"
security_token: "{{ assumed_role.sts_creds.session_token }}"
region: "{{ aws_region }}"
image: "{{ image_instance }}"
instance_type: "{{ large_instance }}"
key_name: "{{ ssh_keyname }}"
count: "{{ ninstances }}"
state: present
group_id: "{{ cypher_priv_sg }}"
vpc_subnet_id: "{{ private_subnet_id }}"
instance_profile_name: 'Cypher-Ansible'
wait: true
instance_tags:
Name: Cypher-Worker
#delete_on_termination: yes
register: ec2
ignore_errors: True
然后终止任务是:
- name: Terminate instances that were previously launched
connection: local
become: false
ec2:
state: 'absent'
instance_ids: '{{ ec2.instance_ids }}'
region: '{{ aws_region }}'
register: TerminateWorker
ignore_errors: True
但是,它不会终止我的Worker实例,而是抛出一个错误:
TASK [Terminate instances that were previously launched] ***********************
task path: /path/to/file/Ansible/provision.yml:373
fatal: [x.y.a.202]: FAILED! => {
"msg": "The task includes an option with an undefined variable. The error was: 'ec2' is undefined\n\nThe error appears to have been in '/path/to/file/Ansible/provision.yml': line 373, column 7, but maybe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: Terminate instances that were previously launched\n ^ here\n\nexception type: <class 'ansible.errors.AnsibleUndefinedVariable'>\nexception: 'ec2' is undefined"
}
这可能是什么问题?
答案 0 :(得分:3)
你的任务看起来很好看。但为什么要使用&#34;连接&#34;并且&#34;成为&#34;终止时的标志?只是问,因为你没有在配置任务中使用它们。
EDIT2:您的配置和终止任务是否在同一个游戏中?如果是,您可以访问已注册的&#34; ec2&#34;像这样的变量:
- name: Terminate instances that were previously launched
ec2:
state: 'absent'
instance_ids: '{{ item.instance_id }}'
region: "{{ aws_region }}"
wait: yes
wait_timeout: 500
with_items: "{{ ec2.instances }}"
如果你的终止任务是同一个剧本的另一个游戏,你必须使用 set_fact 任务使其可以进行其他游戏。
如果您的终止任务将在完全不同的Playbook中执行,您可以使用 ec2_instance_facts 找到您的实例ID,如下所示:
- name: get ec2 instance id by its name tag
ec2_instance_facts:
filters:
"tag:ec2_instance_name": "{{ ecs_instance_name }}"
instance-state-name: running
register: instances
使用此方法,您必须通过配置任务设置上述标记。
答案 1 :(得分:0)
您需要在该任务中指定ec2 var为ise。
你可以加:
with_items: {{ ec2 }}
在您的终止任务结束时,它将从上述任务中的注册变量中选择它。