【发布时间】:2021-06-20 21:24:55
【问题描述】:
我想将客户端系统上的 ssh 服务器端口更改为自定义的 2202(在group_var/all 和roles/change-sshd-port/vars/main.yml 中定义的端口)。我的要求是当端口已经设置为自定义 2202 时也可以运行 playbook(然后 playbook 应该什么都不做)。
我已经根据解决方案使用了ansible角色:https://github.com/Forcepoint/fp-pta-ansible-change-sshd-port
第一次运行脚本时端口更改正常(完成后我可以在新端口上登录客户端节点)。
当我再次运行 playbook 时它失败了,因为它试图通过旧的 22 而不是新的端口 2202 执行一些任务
TASK [change-sshd-port : Confirm host connection works] ********************************************************************************************************************
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}
当ansible_port 变量设置为roles/change-sshd-port/vars/main.yml 中的新端口时,我找不到它为何尝试使用端口22
---
# vars file for /home/me/ansible2/roles/change-sshd-port
ansible_port: 2202
角色任务roles/change-sshd-port/tasks/main.yml直到失败ping任务的部分是:
- name: Set configured port fact
ansible.builtin.set_fact:
configured_port: "{{ ansible_port }}"
- name: Check if we're using the inventory-provided SSH port
ansible.builtin.wait_for:
port: "{{ ansible_port }}"
state: "started"
host: "{{ ansible_host }}"
connect_timeout: "5"
timeout: "10"
delegate_to: "localhost"
ignore_errors: "yes"
register: configured_ssh
- name: SSH port is configured properly
ansible.builtin.debug:
msg: "SSH port is configured properly"
when: configured_ssh is defined and
configured_ssh.state is defined and
configured_ssh.state == "started"
register: ssh_port_set
- name: Check if we're using the default SSH port
ansible.builtin.wait_for:
port: "22"
state: "started"
host: "{{ ansible_host }}"
connect_timeout: "5"
timeout: "10"
delegate_to: "localhost"
ignore_errors: "yes"
register: default_ssh
when: configured_ssh is defined and
configured_ssh.state is undefined
- name: Set inventory ansible_port to default
ansible.builtin.set_fact:
ansible_port: "22"
when: default_ssh is defined and
"state" in default_ssh and
default_ssh.state == "started"
register: ssh_port_set
- name: Fail if SSH port was not auto-detected (unknown)
ansible.builtin.fail:
msg: "The SSH port is neither 22 or {{ ansible_port }}."
when: ssh_port_set is undefined
- name: Confirm host connection works
ansible.builtin.ping:
【问题讨论】:
-
该主机的清单条目是什么样的?
-
只用一个测试远程客户端测试主机组条目,ansible_port 2202 在角色的变量中提供 - 我在 ansible.cfg 中也将它设置为相同的自定义值 ansible_port=2202(在 ansible.cfg还有 ansible_become=yes)
标签: ansible