boto3 在尝试使用 Ansible 停止 AWS EC2 实例时出错

boto3 gives error when trying to stop an AWS EC2 instance using Ansible

我正在尝试创建一个 ansible 剧本来安装 docker & docker-compose 在主机服务器上,停止和启动 AWS EC2 实例然后重启 docker.

一切顺利,直到我尝试停止实例,然后发生了这种情况:

TASK [docker_setup : Gather facts] ******************************************************************************************************************************************
[DEPRECATION WARNING]: The 'ec2_instance_facts' module has been renamed to 'ec2_instance_info'. This feature will be removed in version 2.13. Deprecation warnings can be 
disabled by setting deprecation_warnings=False in ansible.cfg.
fatal: [172.31.25.50]: FAILED! => {"changed": false, "msg": "boto3 required for this module"} 

剧本中停止实例的步骤如下所示:

- name: Install boto3 and botocore with pip3 module for Gather facts
  pip:
    name:
      - boto3
      - botocore
    executable: pip-3.7

- name: Gather facts
  action: ec2_instance_facts

- name: Stop myserver instance
  local_action:
    module: ec2
    region: "{{region}}"
    instance_ids: "{{ansible_ec2_instance_id}}"
    state: stopped

我安装boto3的原因是因为它抱怨没有安装但是即使安装了它仍然报错。我还在 Internet 上读到我应该在每个主机旁边的 host 文件中添加 ansible_python_interpreter=/usr/bin/python,所以我这样做了。但它没有用。它看起来像这样:

[webservers]
172.31.25.50 ansible_python_interpreter=/usr/bin/python

有什么想法吗?谢谢!

我是如何解决这个问题的:

我了解到您实际上可以通过 vars 将其添加到任务的特定操作中,而不是在主机文件中使用 ansible_python_interpreter

- name: Stop instance(s)
  vars:
    ansible_python_interpreter: /usr/bin/python3
  ec2_instance:
    aws_access_key: xxxxx
    aws_secret_key: xxxxx
    region: "{{region}}"
    instance_ids: "{{ansible_ec2_instance_id}}"
    state: stopped

还在 ansible_python_interpreter 上使用 python3 而不是 python。如果我像以前一样在主机文件上使用 ansible_python_interpreter: /usr/bin/python3,它会给出另一个错误,因为整个任务的默认解释器正在使用它,但这样你可以将它定向到你想使用它的时候。