LoginSignup
0
1

More than 3 years have passed since last update.

Ansible初期設定 SSH接続

Posted at

0. はじめに

Ansibl実行時に管理サーバと管理対象サーバ間でSSH接続し、構成管理を行う。
この記事では、管理サーバ上の一般ユーザと管理対象サーバのroot間のSSH接続初期設定をplaybookで実行する方法を記載する。

1. 準備

管理対象サーバにAnsibleをインストール。

ansible --version
ansible 2.9.11
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Apr 16 2020, 01:36:27) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5)]

2. 管理サーバに一般ユーザを作成

playbookに以下タスクを記載し、一般ユーザを作成する。この時、userモジュールでssh鍵も作成する。
※localでの実行のため、実行のためにSSHの接続準備等は不要。

- name: make group
  group:
    name: "{{ item }}"
  loop: "{{ test_ID }}"

- name: make user
  user:
    name: "{{ item }}"
    group: "{{ item }}"
    generate_ssh_key: yes
    ssh_key_bits: 2048
    ssh_key_file: ".ssh/id_XXXX_rsa"
  loop: "{{ test_ID }}"

3. SSH接続用playbookを作成

初期接続設定のため、connectionをparamikoと設定し公開鍵登録のためのplaybookを作成。

- hosts: ap_server
  connection: paramiko
  tasks:
    - name: ssh
      authorized_key:
        user: root
        state: present
        key: "{{ lookup('file', '/home/{{ ID }}/.ssh/id_XXXX_rsa.pub') }}"

併せて、SSHの設定ファイルの配置も行う。

- name: config
  copy:
    src: /work/files/config
    dest: /home/{{ item }}/.ssh/config
    mode: '0600'
    owner: "{{ item }}"
    group: "{{ item }}"
  loop: "{{ test_ID }}"

configファイルでは秘密鍵のパスを設定。

Host (管理対象サーバのホスト名 or IP)
  IdentityFile ~/.ssh/id_XXXX_rsa(秘密鍵のパス)

4. inventory 作成

Inventoryに管理対象サーバの情報を記載。

[ap_server]
test_server ansible_ssh_user=root ansible_ssh_pass=XXXXXXXX

5. ansible.cfg修正

接続にparamikoを利用するため、接続時に自動でhost keyを書き込む設定を有効化。

# When using persistent connections with Paramiko, the connection runs in a
# background process.  If the host doesn't already have a valid SSH key, by
# default Ansible will prompt to add the host key.  This will cause connections
# running in background processes to fail.  Uncomment this line to have
# Paramiko automatically add host keys.
host_key_auto_add = True

6. 実行結果

1.で作成したユーザに切り替え、playbookを実行。

ansible-playbook -i inventory playbook.yml

検証
検証用として、以下playbookを作成し実行。
inventoryファイルはパスワードの記載していないものに修正すること。

---
- hosts: ap_server
  tasks:
    - file:
        state: directory
        path: /tmp

上記playbookの実行に成功。SSH接続が適切に実施されたことが確認できた。

ansible-playbook -i inventory test.yml
~(省略)~
PLAY RECAP *********************************************************************
test_server              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
0
1
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
0
1