如何在 Ansible 中輕松實(shí)現(xiàn)復(fù)雜 SSH 跳轉(zhuǎn)?這個(gè)參數(shù)搞定
在日常的運(yùn)維工作中,我們經(jīng)常會(huì)遇到需要通過跳板機(jī)來訪問目標(biāo)主機(jī)的情況。那么,如何高效地配置Ansible以支持多級(jí)跳轉(zhuǎn)或復(fù)雜的 SSH 設(shè)置呢?ansible_ssh_common_args 提供了一個(gè)非常靈活的解決方案。在這篇文章中,我們將詳細(xì)探討它的功能,并通過一些實(shí)際案例來幫助你快速上手。希望這些內(nèi)容能對(duì)你有所幫助!
什么是ansible_ssh_common_args
ansible_ssh_common_args是Ansible中用于定義SSH額外參數(shù)的變量。這些參數(shù)會(huì)在Ansible執(zhí)行任務(wù)時(shí)傳遞給底層的ssh命令,從而實(shí)現(xiàn)定制化的連接配置。
常見用途:
- 實(shí)現(xiàn)跳板機(jī)連接。
- 提供給ssh、sftp、scp命令的額外參數(shù)
- 調(diào)試SSH連接或指定特定的密鑰文件。
基本語法和配置
ansible_ssh_common_args的值必須符合SSH的參數(shù)格式,例如-o選項(xiàng)。
定義方式:
① 在hosts清單中配置:
[target]
target_host ansible_host=192.168.2.101 ansible_ssh_common_args='-o ProxyCommand="sshpass -p password ssh -W %h:%p -q user@192.168.1.100"'
參數(shù)含義:
- target_host: 主機(jī)組中的主機(jī)別名。
- ansible_host: 指定目標(biāo)主機(jī)的實(shí)際IP地址。
- ansible_ssh_common_args:定義了Ansible在SSH連接時(shí)使用的額外參數(shù) 。
- ProxyCommand 是SSH的一個(gè)選項(xiàng),表示通過代理命令來處理連接。
- sshpass: 是一個(gè)工具,用于通過明文密碼非交互式地登錄SSH。
- -W %h:%p : 將目標(biāo)主機(jī)的地址%h和端口%p直接轉(zhuǎn)發(fā)到跳板機(jī) 。
- -q:靜默模式,禁止顯示SSH的警告信息。
② 在Playbook中定義:
- name:UseProxyJumptoaccesstargethost
hosts:all
vars:
ansible_ssh_common_args:'-o ProxyCommand="sshpass -p password ssh -W %h:%p -q user@192.168.1.100"'
tasks:
-name:Pingtargethost
ping:
③ 在ansible.cfg配置文件中全局定義:
[ssh_connection]
ssh_args = -o ProxyCommand="sshpass -p password ssh -W %h:%p -q user@192.168.1.100"
實(shí)戰(zhàn)案例:實(shí)現(xiàn)復(fù)雜SSH跳轉(zhuǎn)
場(chǎng)景描述
我們有以下需求:
- 通過跳板機(jī) 192.168.1.253 訪問目標(biāo)主機(jī) 192.168.31.101。
- 跳板機(jī)和目標(biāo)主機(jī)的用戶名和密碼均不同。
- 未設(shè)置免密登錄,需要提供密碼。
案例 1:?jiǎn)渭?jí)跳轉(zhuǎn)
通過跳板機(jī)訪問目標(biāo)主機(jī):
[target]
target_host ansible_host=192.168.31.101 ansible_ssh_pass="didiplus558" ansible_ssh_common_args='-o ProxyCommand="sshpass -p password ssh -W %h:%p -q root@192.168.1.253"'
運(yùn)行命令:
ansible target_hosts -m ping -i hosts
運(yùn)行成功如下圖所示:
案例 2:多級(jí)跳轉(zhuǎn)
需要通過兩級(jí)跳板機(jī)連接目標(biāo)主機(jī):
- 第一跳:通過 192.168.1.252。
- 第二跳:通過 192.168.1.253。
配置文件:
[target_hosts]
host1 ansible_host=192.168.31.101 ansible_ssh_pass="password" ansible_ssh_common_args='-o ProxyCommand="sshpass -p password ssh -W %h:%p -q didiplus@192.168.1.252 -o ProxyCommand=\"sshpass -p password ssh -W %h:%p -q root@192.168.1.253\""'
運(yùn)行命令:
ansible target_hosts -m ping -i hosts
ProxyCommand 實(shí)現(xiàn)了兩級(jí)跳轉(zhuǎn),內(nèi)嵌的ssh命令依次通過兩個(gè)跳板機(jī)轉(zhuǎn)發(fā)到目標(biāo)主機(jī)。
總結(jié)
通過ansible_ssh_common_args,我們可以在Ansible中輕松實(shí)現(xiàn)復(fù)雜的SSH配置,包括多級(jí)跳板機(jī)跳轉(zhuǎn)等。結(jié)合實(shí)際場(chǎng)景的靈活應(yīng)用,可以大幅提升運(yùn)維效率。希望通過本文的案例,你能熟練掌握該參數(shù)的使用,為日常工作帶來更多便利!