使用“delegate_to: "localhost"
”的任务试图将“localhost”而不是从“localhost”(ansible master)ssh到远程的ssh端口,这是正确的行为吗?
Playbook 失败:
"Timeout when waiting for localhost:2022"
这里是我复制的示例配置:
库存文件:
[testremote]
192.168.170.113 ansible_user=ja
Ansible 配置文件:
[defaults]
host_key_checking = False
inventory = hosts
callback_enabled = profile_tasks
ansible_port = 2022
剧本文件:
- hosts: testremote
gather_facts: false
vars:
desired_port: 2022
tasks:
- name: check if ssh is running on {{ desired_port }}
delegate_to: localhost
wait_for:
port: "{{ desired_port }}"
host: "{{ ansible_host }}"
timeout: 10
ignore_errors: true
register: desired_port_check
- when: desired_port_check is success
block:
- debug:
msg: "ssh is running on desired port"
- name: configure ansible to use port {{ desired_port }}
set_fact:
ansible_port: "{{ desired_port }}"
- name: run a command on the target host
command: uptime
register: uptime
- debug:
msg: "{{ uptime.stdout }}"
远程主机已可在所需端口上访问:
[ansible]$ ssh -p 2022 ja@testremote date
Sun Jun 20 16:40:36 CEST 2021
[ansible]$ ping testremote
PING testremote (192.168.170.113) 56(84) bytes of data.
64 bytes from testremote (192.168.170.113): icmp_seq=1 ttl=63 time=1.14 ms
运行剧本时的结果:
[ansible]$ ansible-playbook test_playbook.yml
PLAY [testremote] **********************************************************************************************************************************************************
TASK [check if ssh is running on 2022] *************************************************************************************************************************************
fatal: [192.168.170.113 -> localhost]: FAILED! => {"changed": false, "elapsed": 10, "msg": "Timeout when waiting for localhost:2022"}
...ignoring
TASK [debug] ***************************************************************************************************************************************************************
skipping: [192.168.170.113]
TASK [configure ansible to use port 2022] **********************************************************************************************************************************
skipping: [192.168.170.113]
TASK [run a command on the target host] ************************************************************************************************************************************
fatal: [192.168.170.113]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.170.113 port 22: Connection refused", "unreachable": true}
PLAY RECAP *****************************************************************************************************************************************************************
192.168.170.113 : ok=1 changed=0 unreachable=1 failed=0 skipped=2 rescued=0 ignored=1