如何 运行 使用本地主机在组中的所有主机上使用 Ansible AWX 播放

How to run plays using Ansible AWX on all hosts in a group using localhost

我正在尝试创建一个剧本来创建一些 AWS Windows 服务器的 EC2 快照。我在理解如何获得正确的指令以确保事情尽可能 运行ning 时遇到了很多麻烦。我需要做的是:

我过去曾在另一组 Linux 服务器上完成过此操作,没有出现任何问题。但我遇到这些问题的事实让我觉得这并没有像我想的那样工作(我对所有事情都很陌生 Ansible/AWX)。

第一步是我需要识别通常关闭的实例并打开它们,然后拍摄快照,如果它们通常关闭,则再次关闭它们。所以这是我的 main.yml:

---
- name: start the instance if the default state is stopped
  import_playbook: start-instance.yml
  when: default_state is defined and default_state == 'stopped'

- name: run the snapshot script
  import_playbook: instance-snapshot.yml

- name: stop the instance if the default state is stopped
  import_playbook: stop-instance.yml
  when: default_state is defined and default_state == 'stopped'

这是start-instance.yml

---
- name: make sure instances are running
  hosts: all
  gather_facts: false
  connection: local
  tasks:
    - name: start the instances
      ec2:
        instance_id: "{{ instance_id }}"
        region: "{{ aws_region }}"
        state: running
        wait: true
      register: ec2
    - name: pause for 120 seconds to allow the instance to start
      pause: seconds=120

当我运行这个时,我得到以下错误:

fatal: [myhost,mydomain.com]: UNREACHABLE! => {
    "changed": false,
    "msg": "ssl: HTTPSConnectionPool(host='myhost,mydomain.com', port=5986): Max retries exceeded with url: /wsman (Caused by ConnectTimeoutError(<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f99045e6bd0>, 'Connection to myhost,mydomain.com timed out. (connect timeout=30)'))",
    "unreachable": true

我已经知道这意味着它确实在尝试连接到每个 Windows 主机,这不是我想要的。但是,我认为让 connection: local 解决了这个问题,因为它似乎与我拥有的另一个使用相同剧本的模板一样。

所以如果我将 start-instance.yml 改为说“connection: localhost”,那么播放 运行s - 但会跳过这些步骤,因为它确定没有主机满足条件(即default_state is defined and default_state == 'stopped')。这告诉我该游戏 运行 正在使用 localhost 来 运行 游戏,但也 运行 是针对 localhost 而不是 AWX 清单中的主机列表。

我的主机在 AWX 中定义了变量,例如实例 ID、区域、默认状态。我知道在正常的 Ansible 使用中,我们会在剧本中有实例 ID,这就是 Ansible 知道要启动哪些 AWS 实例的方式,但在这种情况下,我需要它从 AWX 获取此信息。

有什么办法吗?因此,运行 使用 localhost 针对我的 AWX 清单中的所有主机执行任务(启动实例,暂停 120 秒)?

最后我用了delegate_to。我将代码更改为:

---
- name: make sure instances are running
  hosts: all
  gather_facts: false
  tasks:
    - name: start the instances
      delegate_to: localhost
      ec2:
        instance_id: "{{ instance_id }}"
        region: "{{ aws_region }}"
        state: running
        wait: true
      register: ec2
    - name: pause for 120 seconds to allow the instance to start
      pause: seconds=120

并且 AWX 正确地使用 localhost 来 运行 我添加委托的任务。

值得注意的是,我卡住了一段时间才意识到我的模板需要两套凭据——一套 IAM 用户对 运行 AWS 命令​​具有正确的权限,另一套用于 [=18] 的机器凭据=] 实例。