You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible:如何为特定主机组及单个主机分别应用不同的SSH配置?

如何为不同目标主机/组应用特定SSH配置Playbook?

针对你的需求,咱们可以把Playbook拆成两个独立的play块,分别对应group1主机组和单独的host1.abc.com,这样就能精准给每个目标应用对应的SSH配置了。下面是具体的实现方式:

方式一:直接在task中写死配置项

这种方式适合配置项比较简单、不需要复用的场景:

---
# 为group1组内所有主机应用ssh_config1
- name: Apply ssh_config1 to hosts in group1
  hosts: group1
  tasks:
    - name: Add ssh_config1 settings for current host
      community.general.ssh_config:
        ssh_config_file: "{{ ssh_config_path }}"
        host: "{{ inventory_hostname }}"  # 自动获取当前执行的主机名,不用手动逐个编写
        state: present
        # 下面替换成ssh_config1的具体配置参数
        user: "admin"
        identityfile: "~/.ssh/id_rsa_group1"
        port: 2222
        forwardagent: "yes"

# 为host1.abc.com应用ssh_config2(它不属于group1)
- name: Apply ssh_config2 to host1.abc.com
  hosts: host1.abc.com
  tasks:
    - name: Add ssh_config2 settings for host1.abc.com
      community.general.ssh_config:
        ssh_config_file: "{{ ssh_config_path }}"
        host: "{{ inventory_hostname }}"
        state: present
        # 下面替换成ssh_config2的具体配置参数
        user: "devuser"
        identityfile: "~/.ssh/id_rsa_host1"
        port: 22
        stricthostkeychecking: "no"

方式二:用变量复用配置项(更易维护)

如果ssh_config1和ssh_config2的配置项需要复用或者后续可能修改,推荐把配置项定义成变量,然后在task中引用:

首先,你可以在inventory文件或者专门的vars文件里定义配置变量:

# 示例vars文件(比如vars/ssh_configs.yml)
ssh_config1_settings:
  user: "admin"
  identityfile: "~/.ssh/id_rsa_group1"
  port: 2222
  forwardagent: "yes"

ssh_config2_settings:
  user: "devuser"
  identityfile: "~/.ssh/id_rsa_host1"
  port: 22
  stricthostkeychecking: "no"

然后编写Playbook:

---
- name: Apply ssh_config1 to group1 hosts
  hosts: group1
  vars_files:
    - vars/ssh_configs.yml  # 加载定义好的配置变量
  tasks:
    - name: Add SSH config for group1
      community.general.ssh_config:
        ssh_config_file: "{{ ssh_config_path }}"
        host: "{{ inventory_hostname }}"
        state: present
        "{{ ssh_config1_settings }}"  # 直接引用ssh_config1的配置变量

- name: Apply ssh_config2 to host1.abc.com
  hosts: host1.abc.com
  vars_files:
    - vars/ssh_configs.yml
  tasks:
    - name: Add SSH config for host1.abc.com
      community.general.ssh_config:
        ssh_config_file: "{{ ssh_config_path }}"
        host: "{{ inventory_hostname }}"
        state: present
        "{{ ssh_config2_settings }}"  # 引用ssh_config2的配置变量

注意事项

  • 确保ssh_config_path变量已经正确定义(可以通过inventory、vars文件或者命令行-e ssh_config_path=/path/to/ssh/config传入)
  • 提前安装community.general集合:执行ansible-galaxy collection install community.general即可

内容的提问来源于stack exchange,提问作者user1787812

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:27:32