2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

2段 ssh 設定と root ログイン設定

Posted at

はじめに

VScode などで踏み台を経由したリモートサーバのコード管理や、そのサーバの root でのコード管理を行いたいため、
1回の ssh コマンド実施で多段の ssh を実行できるようにした
ssh の config 設定などをしたので、やったことを記載する

実施概要図

1段目のサーバ(ここでは bastion)を踏み台に、2段目サーバ(ここでは ansible) にログインする

さらに 2段目サーバで root ログインも可能にする
(/etc/配下などのコードを管理したいとき用. これはやりようが他にも色々あると思うが、ここでは ssh root@localhost をしている)

スクリーンショット 2021-08-08 15.41.46.png

設定・実施

~/.ssh/config に設定を実施する

~/.ssh/config
# 1段目
Host bastion
  HostName [踏み台サーバ(1段目)のIPまたは名前解決可能なhost名]
  Port 22
  User [踏み台サーバ(1段目)のユーザ名]
  IdentityFile ~/.ssh/id_rsa #鍵を指定して実施する場合
  ForwardAgent yes #localのsshキーを使う場合はこれをつける

# 2段目
Host ansible
  HostName [踏み台サーバ(2段目)のIPまたは名前解決可能なhost名]
  Port 22
  User [踏み台サーバ(2段目)のユーザ名]
  ProxyCommand ssh -W %h:%p bastion
  # ForwardAgent yes #localのsshキーを使う場合はこれをつける

# 2段目rootログイン (3段目)
Host ansible_root
  HostName localhost
  Port 22
  User root
  ProxyCommand ssh -W %h:%p ansible

2段目のサーバに root への直接SSHログインを禁止している場合は、
localhost (127.0.0.1) からは許可できるように sshd_config へ下記設定も追記する
(設定したら sshd のリスタート(systemctl restart sshd)も実施する)

/etc/ssh/sshd_config(最後に追記)
Match Address  127.0.0.1
    PermitRootLogin yes

上記設定を ansible で設定すると下記のような感じ

tasks/main.yaml
  - name: Permit localhost root login
    lineinfile:
      dest: /etc/ssh/sshd_config
      line: "{{ item }}"
    with_items:
      - "Match Address  127.0.0.1"
      - "    PermitRootLogin yes"
    become: yes
    register: sshd_config_result

  - name: restart sshd
    when: sshd_config_result is changed
    systemd:
      name: sshd
      state: restarted
    become: yes

上記設定により ssh コマンド 1回で直接2段目のサーバへログインが可能になる

下記が ssh 実行での出力例 (user2が2段目サーバユーザ名、192.168.129.1が2段目サーバIP例,ansible01が2段目ホスト名)
(ここでは 1段目にsshキーをnopassのをauthorized_keyにしているため1回しか聞かれてない)

ログイン例
% ssh ansible
user2@192.168.129.1's password: 
Last login: Sun Aug  8 15:00:47 2021 from 172.18.0.8
ANSIBLE01 /home/user2% 

root ログインも下記のように可能 (rootのパスワードも聞かれる)

ログイン例(root)
% ssh ansible_root
user2@192.168.129.1's password: 
root@localhost's password: 
Last login: Sun Aug  8 15:16:43 2021 from 127.0.0.1
[root@ansible01 ~]#

VScode でも拡張で Visual Studio Code Remote - SSH を入れていれば、
下記のように~.ssh/configに設定したホスト名が出てくるのでクリックして開けるようになる
(出てこない場合は、⚙歯車マークをクリックして設定した ~/.ssh/config を指定する)

スクリーンショット 2021-08-08 15.27.46.png

おわりに

多段 ssh および root ログインを ssh 設定でコマンド一回ででできるように設定した
これより VScode でもリモートのコード管理ができるようになった

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?