【ハンズオン】GitLabおよびAnsibleによるインフラCI/CD ~Step2.環境構築~

はじめに

アプリケーション開発におけるCI/CDは一般的に広く活用されていますが、インフラレイヤにおけるCI/CDについては、まだ導入が進んでいない現場も多いと感じています。本シリーズでは、GitLabおよびAnsibleを用いたインフラCI/CDの導入例をハンズオン形式でご紹介しますので、ぜひ参考にしていただければ幸いです。今回はStep2としてGitLab、GitLab Runner、Ansibleの構築手順について説明しますので、実際に取り組んで理解を深めていただければと思います。
ステップ1を読んでない方はぜひ読んでみて下さい。
【ハンズオン】GitLabおよびAnsibleによるインフラCI/CD ~Step1.導入目的~

1.前提環境

今回のハンズオンで構築する環境は下記の通りになります。

・コントロールノード
VirtualBoxにCentOSインストールしております。本手順については今回のハンズオン対象外となりますので下記などを参考に準備をしてください。
【VirtualBox】ゲストOS(CentOS)のネットワーク設定 ~SSH接続/インターネット接続~
今回のハンズオンではCentOSの上にインフラCI/CDで使うGitLab、GitLab Runnuer、Ansibleをインストールしていきます。

・ターゲットノード
今回は開発環境と本番環境の2つを適用対象としています。現時点では何かしらのOSをインストールした仮想マシンを準備してください。私はAlmaLinux 9.5をインストールしてみました。

2.Gitlabインストールおよび設定(コントロールノード)

 まずはGitLabインストールのためのリポジトリをセットアップします。下記の通りスクリプトをダウンロードして実行します。

[root@gitlab-server ~]# curl -O https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  7939  100  7939    0     0  27470      0 --:--:-- --:--:-- --:--:-- 27565
[root@gitlab-server ~]# sh ./script.rpm.sh
Detected operating system as centos/8.
Checking for curl...
Detected curl...
Downloading repository file: https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/config_file.repo?os=centos&dist=8&source=script
done.
Installing yum-utils...
CentOS Linux 8 - AppStream                                                                                                                                                                                                    14 kB/s | 4.3 kB     00:00
CentOS Linux 8 - BaseOS

~~Ommit~~

 From       : https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey/gitlab-gitlab-ce-3D645A26AB9FBD22.pub.gpg
Importing GPG key 0x82DD593D:
 Userid     : "GitLab, Inc. <support@gitlab.com>"
 Fingerprint: 98BF DB87 FCF1 0076 416C 1E0B AD99 7ACC 82DD 593D
 From       : https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey/gitlab-gitlab-ce-CB947AD886C8E8FD.pub.gpg
Generating yum cache for gitlab_gitlab-ce-source...

The repository is setup! You can now install packages.
[root@gitlab-server ~]#

続いてdnfコマンドでGitlabをインストールします

[root@gitlab-server ~]# dnf -y install gitlab-ce
Last metadata expiration check: 0:01:09 ago on Wed 07 May 2025 06:41:17 AM JST.
Dependencies resolved.
=============================================================================================================================================================================================================================================================
 Package                                                   Architecture                                           Version                                                             Repository                                                        Size
=============================================================================================================================================================================================================================================================
Installing:
 gitlab-ce                                                 x86_64                                                 17.11.1-ce.0.el8                                                    gitlab_gitlab-ce                                                 1.4 G

Transaction Summary
=============================================================================================================================================================================================================================================================
Install  1 Package

Total download size: 1.4 G
Installed size: 3.6 G
Downloading Packages:
gitlab-ce-17.11.1-ce.0.el8.x86_64.rpm                                                                                                                                                                                         25 MB/s | 1.4 GB     00:57
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                                                                         25 MB/s | 1.4 GB     00:57
gitlab_gitlab-ce                                                                                                                                                                                                             6.1 kB/s | 3.1 kB     00:00
Importing GPG key 0x51312F3F:
 Userid     : "GitLab B.V. (package repository signing key) <packages@gitlab.com>

~~Ommit~~

It looks like GitLab has not been configured yet; skipping the upgrade script.

       *.                  *.
      ***                 ***
     *****               *****
    .******             *******
    ********            ********
   ,,,,,,,,,***********,,,,,,,,,
  ,,,,,,,,,,,*********,,,,,,,,,,,
  .,,,,,,,,,,,*******,,,,,,,,,,,,
      ,,,,,,,,,*****,,,,,,,,,.
         ,,,,,,,****,,,,,,
            .,,,***,,,,
                ,*,.



     _______ __  __          __
    / ____(_) /_/ /   ____ _/ /_
   / / __/ / __/ /   / __ `/ __ \
  / /_/ / / /_/ /___/ /_/ / /_/ /
  \____/_/\__/_____/\__,_/_.___/


Thank you for installing GitLab!
GitLab was unable to detect a valid hostname for your instance.
Please configure a URL for your GitLab instance by setting `external_url`
configuration in /etc/gitlab/gitlab.rb file.
Then, you can start your GitLab instance by running the following command:
  sudo gitlab-ctl reconfigure

For a comprehensive list of configuration options please see the Omnibus GitLab readme

README.md · master · GitLab.org / omnibus-gitlab · GitLab
This project creates full-stack platform-specific downloadable packages for GitLab.
Help us improve the installation experience, let us know how we did with a 1 minute survey:
Online Survey Software | Qualtrics Survey Solutions
Qualtrics makes sophisticated research simple and empowers users to capture customer, product, brand & employee experien...
Verifying : gitlab-ce-17.11.1-ce.0.el8.x86_64 1/1 Installed: gitlab-ce-17.11.1-ce.0.el8.x86_64 Complete! [root@gitlab-server ~]#

インストールが完了したらgitlab-ctl reconfigureコマンドを実行してGitlabの設定を自動で実行します。20分~30分くらいかかりますのでしばらく放置して下さい。ちなみにgitlab-ctl reconfigureコマンドで実行しているのは主に下記となります。
・各種設定ファイル、ディレクトリの生成および権限変更
・各種コンポーネント(PostgreSQL、nginxなど)の設定および初期化

[root@gitlab-server ~]# gitlab-ctl reconfigure
[2025-05-07T06:47:24+09:00] INFO: Started Cinc Zero at chefzero://localhost:1 with repository at /opt/gitlab/embedded (One version per cookbook)
Cinc Client, version 18.3.0
Patents: https://www.chef.io/patents
Infra Phase starting

~~Ommit~~

Running handlers:
[2025-05-07T07:38:30+09:00] INFO: Running report handlers
Running handlers complete
[2025-05-07T07:38:30+09:00] INFO: Report handlers complete
Infra Phase complete, 578/1609 resources updated in 07 minutes 10 seconds

Notes:
Default admin account has been configured with following details:
Username: root
Password: You didn't opt-in to print initial root password to STDOUT.
Password stored to /etc/gitlab/initial_root_password. This file will be cleaned up in first reconfigure run after 24 hours.

NOTE: Because these credentials might be present in your log files in plain text, it is highly recommended to reset the password following https://docs.gitlab.com/ee/security/reset_user_password.html#reset-your-root-password.

gitlab Reconfigured!
[root@git-server ~]#

GitLabのインストール手順は以上となります。続いてブラウザからGitLabの管理画面にアクセスしてみて下さい。GitLabをインストールしたサーバーのホスト名あるいはIPアドレスを指定してアクセスします。私の場合はhttp://192.168.56.101となります。下記の通りGitLabの画面が出力されていればOKです。

rootユーザのパスワードがわからないのでサーバー上で確認をしましょう。initial_root_passwordファイルのPassword:という項目に記載されているテキスト(私の環境ではGJXmUXOqsQh5MsRc6d0DX8Ocwz6TL1wQGlB8ynC612A=)がrootユーザーのパスワードとなります。

[root@git-server ~]# cat /etc/gitlab/initial_root_password
# WARNING: This value is valid only in the following conditions
#          1. If provided manually (either via `GITLAB_ROOT_PASSWORD` environment variable or via `gitlab_rails['initial_root_password']` setting in `gitlab.rb`, it was provided before database was seeded for the first time (usually, the first reconfigure run).
#          2. Password hasn't been changed manually, either via UI or via command line.
#
#          If the password shown here doesn't work, you must reset the admin password following https://docs.gitlab.com/ee/security/reset_user_password.html#reset-your-root-password.

Password: GJXmUXOqsQh5MsRc6d0DX8Ocwz6TL1wQGlB8ynC612A=

# NOTE: This file will be automatically deleted in the first reconfigure run after 24 hours.
[root@git-server ~]#

ユーザー名「root」、パスワードは先ほど調べた値でログインしてみて下さい。下記画面が出力されればOKです。

続いて実際に使うユーザーを登録していきます。「Admin」アイコンをクリックしてください。

「User」をクリックします。

「New user」をクリックします。

Name、Username、Emailを入力します。

Administratorを指定して「Create User」をクリックします。

下記の通りユーザーが正常に作成された旨のメッセージが出ていればOKです。
続いて初期パスワードを設定します。「Users」をクリックしてください。

Password欄に初期パスワードを入力して「Save changes」ボタンをクリックします。

続いて作成したユーザーでログインできるかどうか確認しましょう。まずrootユーザーからサインアウトしてください。

先ほど作成したユーザー名と設定した初期パスワード入力してサインインしてください。

パスワード変更が求められるので、変更した上でサインインします。下図の通り作成したユーザーでログインできていれば成功です。

続けて、プロジェクト(リポジトリー)の作成を行います。 rootユーザでGitLabにログインしてください。下図通り「+」ボタンを押下して「New project/repository」を選択します。

「Create blank project」を押下します。

Project name、Project URLを入力します。要件に応じてVisibility Levelを選択してください。私の環境ではPublicを選択し、制限なく誰からでもアクセスできるようにしています。最後に「Create project」ボタンを押下します。

下記の通り指定したProjectが作成できていれば成功です。

3.Gitlab Runnerインストールおよび設定(コントロールノード)

続いてGitLab-runnerをインストールします。まずリポジトリをインストールします。

[root@git-server ~]# curl -O https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.rpm.sh
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  7983  100  7983    0     0  25423      0 --:--:-- --:--:-- --:--:-- 25586
[root@git-server ~]#
[root@git-server ~]# sh ./script.rpm.sh
Detected operating system as centos/8.
Checking for curl...
Detected curl...
Downloading repository file: https://packages.gitlab.com/install/repositories/runner/gitlab-runner/config_file.repo?os=centos&dist=8&source=script
done.
Installing yum-utils...
runner_gitlab-runner-source                                                                                                                                                                                                  479  B/s | 862  B     00:01
runner_gitlab-runner-source                                                                                                                                                                                                  6.8 kB/s | 3.1 kB     00:00
Importing GPG key 0x51312F3F:
 Userid     : "GitLab B.V. (package repository signing key) <packages@gitlab.com>"
 Fingerprint: F640 3F65 44A3 8863 DAA0 B6E0 3F01 618A 5131 2F3F
 From       : https://packages.gitlab.com/runner/gitlab-runner/gpgkey
runner_gitlab-runner-source                                                                                                                                                                                                  8.2 kB/s | 3.1 kB     00:00

~~Ommit~~

Importing GPG key 0x6BA75A4E:
 Userid     : "GitLab, Inc. <support@gitlab.com>"
 Fingerprint: 931D A69C FA3A FEBB C97D AA8C 6C57 C29C 6BA7 5A4E
 From       : https://packages.gitlab.com/runner/gitlab-runner/gpgkey/runner-gitlab-runner-49F16C5CC3A0F81F.pub.gpg
Generating yum cache for runner_gitlab-runner-source...

The repository is setup! You can now install packages.
[root@git-server ~]#

dnfコマンドでgitlab-runnerをインストールします。

[root@git-server ~]# dnf install -y gitlab-runner
gitlab_gitlab-ce                                                                                                                                                                                                             497  B/s | 862  B     00:01
gitlab_gitlab-ce-source                                                                                                                                                                                                      603  B/s | 862  B     00:01
runner_gitlab-runner                                                                                                                                                                                                         493  B/s | 862  B     00:01
runner_gitlab-runner-source                                                                                                                                                                                                  529  B/s | 862  B     00:01
Dependencies resolved.
=============================================================================================================================================================================================================================================================
 Package                                                                  Architecture                                        Version                                                Repository                                                         Size
=============================================================================================================================================================================================================================================================
Installing:
 gitlab-runner                                                            x86_64                                              17.11.1-1                                              runner_gitlab-runner                                               25 M
Installing dependencies:
 gitlab-runner-helper-images                                              noarch                                              17.11.1-1                                              runner_gitlab-runner                                              495 M

Transaction Summary
=============================================================================================================================================================================================================================================================
Install  2 Packages

Total download size: 520 M
Installed size: 599 M
Downloading Packages:
(1/2): gitlab-runner-17.11.1-1.x86_64.rpm                                                                                                                                                                                    5.2 MB/s |  25 MB     00:04
(2/2): gitlab-runner-helper-images-17.11.1-1.noarch.rpm                                                                                                                                                                       21 MB/s | 495 MB     00:23
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                                                                         22 MB/s | 520 MB     00:24
runner_gitlab-runner                                                                                                                                                                                                         6.9 kB/s | 3.1 kB     00:00
GPG key at https://packages.gitlab.com/runner/gitlab-runner/gpgkey (0x51312F3F) is already installed

~~Ommit~~

Total reclaimed space: 315MB

  Verifying        : gitlab-runner-17.11.1-1.x86_64                                                                                                                                                                                                      1/2
  Verifying        : gitlab-runner-helper-images-17.11.1-1.noarch                                                                                                                                                                                        2/2

Installed:
  gitlab-runner-17.11.1-1.x86_64                                                                                         gitlab-runner-helper-images-17.11.1-1.noarch

Complete!
[root@git-server ~]#
[root@git-server ~]# gitlab-runner --version

Version:      17.11.1
Git revision: 96856197
Git branch:   17-11-stable
GO version:   go1.23.6 X:cacheprog
Built:        2025-05-05T10:24:25Z
OS/Arch:      linux/amd64
[root@git-server ~]#

gitlab-runnerを起動して状態を確認します。

[root@git-server ~]# systemctl enable --now gitlab-runner
[root@git-server ~]#
[root@git-server ~]# systemctl status gitlab-runner
● gitlab-runner.service - GitLab Runner
   Loaded: loaded (/etc/systemd/system/gitlab-runner.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2025-05-09 07:04:16 JST; 2min 53s ago
 Main PID: 4885 (gitlab-runner)
    Tasks: 8 (limit: 36456)
   Memory: 26.2M
   CGroup: /system.slice/gitlab-runner.service
           └─4885 /usr/bin/gitlab-runner run --config /etc/gitlab-runner/config.toml --working-directory /home/gitlab-runner --service gitlab-runner --user gitlab-runner

May 09 07:04:17 git-server gitlab-runner[4885]: Runtime platform                                    arch=amd64 os=linux pid=4885 revision=96856197 version=17.11.1
May 09 07:04:17 git-server gitlab-runner[4885]: Starting multi-runner from /etc/gitlab-runner/config.toml...  builds=0 max_builds=0
May 09 07:04:17 git-server gitlab-runner[4885]: Running in system-mode.
May 09 07:04:17 git-server gitlab-runner[4885]:
May 09 07:04:17 git-server gitlab-runner[4885]: Created missing unique system ID                    system_id=s_2d64be210598
May 09 07:04:17 git-server gitlab-runner[4885]: Usage logger disabled                               builds=0 max_builds=1
May 09 07:04:17 git-server gitlab-runner[4885]: Configuration loaded                                builds=0 max_builds=1
May 09 07:04:17 git-server gitlab-runner[4885]: listen_address not defined, metrics & debug endpoints disabled  builds=0 max_builds=1
May 09 07:04:17 git-server gitlab-runner[4885]: [session_server].listen_address not defined, session endpoints disabled  builds=0 max_builds=1
May 09 07:04:17 git-server gitlab-runner[4885]: Initializing executor providers                     builds=0 max_builds=1
[root@git-server ~]#

続いてGitlLab RunnerとGitLabを連動させるために、Registration Tokenというトークンを登録します。GUIの管理コンソールからRegistration Tokenを確認できますので、下記の通りトークン情報を取得して下さい。

ターミナルに戻り、gitlab-runner registerコマンドでrunnerをGitLabに登録します。GitLabサーバのURL、先ほど取得したregistration token等の情報を入力して進めます。

[root@git-server ~]# gitlab-runner register
Runtime platform                                    arch=amd64 os=linux pid=3355 revision=96856197 version=17.11.1
WARNING: Running in user-mode.
WARNING: The user-mode requires you to manually start builds processing:
WARNING: $ gitlab-runner run
WARNING: Use sudo for system-mode:
WARNING: $ sudo gitlab-runner...

Enter the GitLab instance URL (for example, https://gitlab.com/):

http://gitlab.example.com/
Enter the registration token: sJ2foS2XsFUVB-sg7J5D Enter a description for the runner: [git-server]: Enter tags for the runner (comma-separated): Ansible Enter optional maintenance note for the runner: WARNING: Support for registration tokens and runner parameters in the 'register' command has been deprecated in GitLab Runner 15.6 and will be replaced with support for authentication tokens. For more information, see https://docs.gitlab.com/ci/runners/new_creation_workflow/ Registering runner... succeeded runner=sJ2foS2X Enter an executor: instance, custom, ssh, parallels, docker, docker-windows, docker-autoscaler, shell, virtualbox, docker+machine, kubernetes: shell Runner registered successfully. Feel free to start it, but if it's running already the config should be automatically reloaded! Configuration (with the authentication token) was saved in "/home/ansible/.gitlab-runner/config.toml" [root@git-server ~]#

Runnersボタンをクリックして状態を確認してください。Onlineになっていれば成功です。

3.Ansibleインストール(コントロールノード)

dnfコマンドでインストールを行います。まずはリポジトリepel-releaseをインストールしてください。ちなみにepelとはExtra Packages for Enterprise Linuxの略となります。

[root@git-server ~]# dnf install -y epel-release
gitlab_gitlab-ce                                                                                                      472  B/s | 862  B     00:01
gitlab_gitlab-ce-source                                                                                               476  B/s | 862  B     00:01
runner_gitlab-runner                                                                                                  428  B/s | 862  B     00:02
runner_gitlab-runner-source                                                                                           467  B/s | 862  B     00:01
Dependencies resolved.
======================================================================================================================================================
 Package                                Architecture                     Version                               Repository                        Size
======================================================================================================================================================
Installing:
 epel-release                           noarch                           8-11.el8                              extras                            24 k

Transaction Summary
======================================================================================================================================================
Install  1 Package

Total download size: 24 k
Installed size: 35 k
Downloading Packages:
epel-release-8-11.el8.noarch.rpm                                                                                       67 kB/s |  24 kB     00:00
------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                  65 kB/s |  24 kB     00:00
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                                              1/1
  Installing       : epel-release-8-11.el8.noarch                                                                                                 1/1
  Running scriptlet: epel-release-8-11.el8.noarch                                                                                                 1/1
  Verifying        : epel-release-8-11.el8.noarch                                                                                                 1/1

Installed:
  epel-release-8-11.el8.noarch

Complete!
[root@git-server ~]#

pip3というPython3用のパッケージ管理ツールを最新版にしておきます。

[root@git-server ~]# pip3 install --upgrade pip
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
Collecting pip
  Downloading https://files.pythonhosted.org/packages/a4/6d/6463d49a933f547439d6b5b98b46af8742cc03ae83543e4d7688c2420f8b/pip-21.3.1-py3-none-any.whl (1.7MB)
    100% |████████████████████████████████| 1.7MB 909kB/s
Installing collected packages: pip
Successfully installed pip-21.3.1
[root@git-server ~]#

Ansibleをインストールします。

[root@git-server ~]# pip3 install ansible
WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
Collecting ansible
  Downloading ansible-4.10.0.tar.gz (36.8 MB)
     |████████████████████████████████| 36.8 MB 11.3 MB/s
  Preparing metadata (setup.py) ... done

~~Omission~~

  Downloading pycparser-2.21-py2.py3-none-any.whl (118 kB)
     |████████████████████████████████| 118 kB 9.4 MB/s
Using legacy 'setup.py install' for ansible, since package 'wheel' is not installed.
Using legacy 'setup.py install' for ansible-core, since package 'wheel' is not installed.
Installing collected packages: pycparser, pyparsing, MarkupSafe, cffi, resolvelib, packaging, jinja2, cryptography, ansible-core, ansible
    Running setup.py install for ansible-core ... done
    Running setup.py install for ansible ... done
Successfully installed MarkupSafe-2.0.1 ansible-4.10.0 ansible-core-2.11.12 cffi-1.15.1 cryptography-40.0.2 jinja2-3.0.3 packaging-21.3 pycparser-2.21 pyparsing-3.1.4 resolvelib-0.5.4
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
[root@git-server ~]#

ansibleのバージョンを確認します。 Pythonのバージョンが古いのでWarningメッセージが出てしまっていますが、2.11.12がインストールされていることが確認できました。

[root@git-server ~]# ansible --version
[DEPRECATION WARNING]: Ansible will require Python 3.8 or newer on the controller starting with Ansible 2.12. Current version: 3.6.8 (default, Sep 10
 2021, 09:13:53) [GCC 8.5.0 20210514 (Red Hat 8.5.0-3)]. This feature will be removed from ansible-core in version 2.12. Deprecation warnings can be
disabled by setting deprecation_warnings=False in ansible.cfg.
/usr/local/lib/python3.6/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography. The next release of cryptography will remove support for Python 3.6.
  from cryptography.exceptions import InvalidSignature
ansible [core 2.11.12]
  config file = None
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.6/site-packages/ansible
  ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/local/bin/ansible
  python version = 3.6.8 (default, Sep 10 2021, 09:13:53) [GCC 8.5.0 20210514 (Red Hat 8.5.0-3)]
  jinja version = 3.0.3
  libyaml = True
[root@git-server ~]#

続いてAnsible用のユーザを作成してパスワードを設定します。本作業はターゲットノード側でも実施してください。

[root@git-server ~]# adduser ansible
[root@git-server ~]# passwd ansible
Changing password for user ansible.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
[root@git-server ~]#

続いてansibleの設定ファイルを作成します。inventoryやroles_pathなどは自身の作りたい環境に合わせて設定してみて下さい。

[root@git-server ~]# su - ansible
[ansible@git-server ~]$
[ansible@git-server ~]$ vi /home/ansible/ansible.cfg
[ansible@git-server ~]$ cat ansible.cfg
[defaults]
remote_user = ansible
host_key_checking = False
timeout = 30
retry_files_enabled = False
interpreter_python = auto_silent
deprecation_warnings = False
roles_path = /home/ansible/websystem/roles

[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False

[ssh_connection]
ssh_args = -o ForwardAgent=yes -o ControlMaster=auto -o ControlPersist=60s
[ansible@git-server ~]$

続いてディレクトリを作成して下さい。一例としてwebsystemというディレクトリの配下に各種ディレクトリ・ファイルを作成していきます。

[ansible@git-server ~]$ mkdir -p /home/ansible/websystem/inventory
[ansible@git-server ~]$ mkdir -p /home/ansible/websystem/roles
[ansible@git-server ~]$ tree
.
├── ansible.cfg
└── websystem
    ├── inventory
    └── roles
3 directories, 1 file
[ansible@git-server ~]$

続いてinventoryファイルを作成します。ターゲットノード(開発/本番)ごとにファイルを作成してください。

[ansible@git-server ~]$ vi /home/ansible/websystem/inventory/dev_inventory.ini
[ansible@git-server ~]$ cat /home/ansible/websystem/inventory/dev_inventory.ini
[websystem]
dev-web1 ansible_host=192.168.56.102
[ansible@git-server ~]$
[ansible@git-server ~]$ vi /home/ansible/websystem/inventory/prod_inventory.ini
[ansible@git-server ~]$ cat /home/ansible/websystem/inventory/prod_inventory.ini
[websystem]
prod-web1 ansible_host=10.0.0.10
[ansible@git-server ~]$

続いてコントロールノードがターゲットノードに接続するために、コントロールノード側で秘密鍵と公開鍵を作成し、ターゲット側に公開鍵を登録します。
まずは下記の通り、コントロールノード側で下記の通り秘密鍵と公開鍵のペアを作成してください。

[ansible@git-server ~]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ansible/.ssh/id_rsa):
Created directory '/home/ansible/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/ansible/.ssh/id_rsa.
Your public key has been saved in /home/ansible/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:zKsnj42N6gPet/Sno2Too7FBXp7Ukf8fcvvY+zw8dnk ansible@git-server
The key's randomart image is:
+---[RSA 3072]----+
|                 |
|       .         |
|      o          |
|     . =         |
|  . o . S        |
| o.+ o   o       |
| .+o+ + . o o . .|
|  .=++oOo .+ = BE|
|  oo+=B**+  +.=oB|
+----[SHA256]-----+
[ansible@git-server ~]$
[ansible@git-server ~]$ ls -l /home/ansible/.ssh
total 8
-rw------- 1 ansible ansible 2602 May 11 08:11 id_rsa
-rw-r--r-- 1 ansible ansible  572 May 11 08:11 id_rsa.pub

続いてssh-copy-idコマンドを実行することで、ターゲットノード(開発/本番)側に鍵を配置します。
※パスワード認証が必要となります。パスワード認証を無効にしている場合は、一時的に有効にしてください。

[ansible@git-server ~]$ ssh-copy-id -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa.pub 192.168.56.102
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/ansible/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
ansible@192.168.56.102's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh -o 'StrictHostKeyChecking=no' '192.168.56.102'"
and check to make sure that only the key(s) you wanted were added.

[ansible@git-server ~]$

ターゲットノード側でauthorized_keysが作成されていることを確認してください。

[root@dev-target-node ~]# ls -l /home/ansible/.ssh/authorized_keys
-rw------- 1 ansible ansible 572 May 15 06:26 /home/ansible/.ssh/authorized_keys
[root@dev-target-node ~]#

最後にパスワードなしで管理者権限コマンドを実行できるように、 visudoコマンドで下記のAnsibleユーザーに関する設定を追加します。

[root@dev-target-node ~]# visudo
[root@dev-target-node ~]# cat /etc/sudoers |grep ansible
## Allow ansible user to run any commands without password
ansible ALL=(ALL) NOPASSWD:ALL
[root@dev-target-node ~]#

以上でAnsibleの設定は完了です。最後にコントロールノードからターゲットノードに対して接続確認してみましょう。下記の通りSUCECSSという文言が返却されればOKです。

[ansible@git-server ~]$ cd /home/ansible/websystem/inventory
[ansible@git-server inventory]$ ansible -i dev_inventory.ini websystem -m ping
/usr/local/lib/python3.6/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography. The next release of cryptography will remove support for Python 3.6.
  from cryptography.exceptions import InvalidSignature
web1i | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
[ansible@git-server inventory]$
[ansible@git-server inventory]$ ansible -i prod_inventory.ini websystem -m ping
/usr/local/lib/python3.6/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography. The next release of cryptography will remove support for Python 3.6.
  from cryptography.exceptions import InvalidSignature
web1i | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

鍵ペアが作成できたら、ssh-copy-idコマンドで公開鍵の名前および権限を変更します。ssh-copy-idコマンドを実行するためにはSSHのパスワード認証を有効にしておく必要があるので、まずはSSHの設定変更を行います。rootユーザにてsshd_configのPasswordAuthenticationの設定をyesに変更し、sshdプロセスを再起動してください。

まとめ

基本的な環境構築は以上となります。次のStep3以降ではWeb3層モデルのサーバに対してインフラCI/CDを適用する方法をご紹介してきますので、ぜひ引き続きトライしてみて下さい。
【ハンズオン】GitLabおよびAnsibleによるインフラCI/CD ~Step3.Playbook適用~

参考文献

インフラCI実践ガイド Ansible/GitLabを使ったインフラ改善サイクルの実現 | 中島 倫明, 佐々木 健太郎, 北山 晋吾, 齊藤 秀喜, 羽深 修 |本 | 通販 | Amazon

コメント