2018年1月29日月曜日

「いまからはじめるAnsible 第1回」で Ansible を触った(Debian9 と Docker で Ansible を試す)

背景

いまからはじめるAnsible 第1回 – インフラ勉強会 イベント共有ポータル を聞いている裏で「実際に触ってみよう」のための環境構築をしていたら、途中で PC が落ちてしまいました。

後半ほとんど話を聞けていないし実際に触れてもいないので、勉強会ログ・チャットログを見ながら独習しました。

その作業記録を残していきます。

前提環境

  • OS : VirtualBox 上の Debian 9
    • 最小構成インストールプラスアルファ
      • sudo
      • ssh

Debian 上に Docke をインストールする

$ # アップグレード
$ sudo apt-get update
$ sudo apt-get upgrade
$ # 必要パッケージのインストール
$ sudo apt install apt-transport-https ca-certificates curl gnupg2 software-properties-common
$ # Docker リポジトリの鍵を登録
$ curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo "$ID")/gpg | sudo apt-key add -
$ # 登録した鍵の確認
$ sudo apt-key fingerprint 0EBFCD88
$ # apt にリポジトリを登録
$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/$(. /etc/os-release; echo "$ID") $(lsb_release -cs) stable"
$ # アップデート
$ sudo apt-get update
$ # Docker, Docker Compose のインストール
$ sudo apt-get docker-ce docker-compose
$ # 今使っているユーザーで実行できるように docker グループに追加
$ sudo gpasswd -a $USER docker

※ docker サービス再起動しても認識してくれなかったのでログインしなおしました。ログインしなおすと sudo 無しで実行できるようになっているはず。

Ansible のインストール

$ sudo apt-get install ansible

「実際に触ってみよう」をやってみる

ホスト 2 つに、 httpd をインストールする演習。

※ Ansible, Docker のインストールは終わっているので、「inventory を書いてみよう」から始める。docker コンテナの起動は playbook を実行する直前に行うように順番を変えました。

inventory を書いてみよう

プロジェクト用ディレクトリを作成

$ mkdir -p ~/project/ansible-101
$ cd ~/project/ansible-101

vi で ./hosts を作る

[testservers]
test01
test02

playbook を書いてみよう

vi で ./site.yml を作る

---
- name: install httpd
  hosts: testservers
  connection: docker
  tasks:
    - name: Install httpd
      yum:
        name: httpd
        state: present

    - name: Start httpd
      systemd:
        name: httpd
        state: started
        enabled: yes

実行してみよう

Docker コンテナを起動する

$ docker run --privileged --rm --name test01 -i -d centos /sbin/init
$ docker run --privileged --rm --name test02 -i -d centos /sbin/init

※ --rm は私が勝手につけました。残ってほしくないコンテナ作るときは便利。

playbook の妥当性確認

ドライランなので最後の httpd 実行で失敗するらしい。

$ ansible-playbook -i hosts site.yml --check

PLAY [install httpd] ***********************************************************

TASK [setup] *******************************************************************
ok: [test02]
ok: [test01]

TASK [Install httpd] ***********************************************************
changed: [test02]
changed: [test01]

TASK [Start httpd] *************************************************************
fatal: [test02]: FAILED! => {"changed": false, "failed": true, "msg": "Could not find the requested service httpd: cannot enable"}
fatal: [test01]: FAILED! => {"changed": false, "failed": true, "msg": "Could not find the requested service httpd: cannot enable"}
        to retry, use: --limit @/home/mikoto/project/ansible-101/site.retry

PLAY RECAP *********************************************************************
test01                     : ok=2    changed=1    unreachable=0    failed=1   
test02                     : ok=2    changed=1    unreachable=0    failed=1

playbook 実行

実際に動かすので、最後の httpd 実行も成功する。

$ ansible-playbook -i hosts site.yml

PLAY [install httpd] ***********************************************************

TASK [setup] *******************************************************************
ok: [test01]
ok: [test02]

TASK [Install httpd] ***********************************************************
changed: [test02]
changed: [test01]

TASK [Start httpd] *************************************************************
changed: [test01]
changed: [test02]

PLAY RECAP *********************************************************************
test01                     : ok=3    changed=2    unreachable=0    failed=0   
test02                     : ok=3    changed=2    unreachable=0    failed=0   

あとは、それぞれのファイルの書き方を勉強しながら試行錯誤していけば Ansible を使えるようになるのではないでしょうかね?

そんな感じでやっていきましょう。

以上。

2017年12月13日水曜日

OpenSSL で CA と証明書を作る

立てようとしている GitLab に HTTPS 接続するために、独自証明書を作る。

環境

  • OS: Debian strech
  • openssl インストール済み

Docker をインストールした Debian9 上で作業をしている。

CA の準備

CA 側でやる作業。

CA 用のディレクトリを作成する

$ # CA 用の設定を編集
$ # '[ CA_default ]' の 'dir = ./demoCA' を 'dir = /var/ssl/ca' に変更
$ # '[ CA_default ]' の 'private_key = $dir/private/cakey.pem' を 'private_key = $dir/private/ca.key' に変更
$ # '[ CA_default ]' の 'certificate = $dir/cacert.pem' を 'private_key = $dir/ca.cert' に変更
$ sudo vim /etc/ssl/openssl.cnf
$ # CA のディレクトリ構成を作成
$ sudo mkdir -p /var/ssl/ca/certs
$ sudo mkdir -p /var/ssl/ca/private
$ sudo mkdir -p /var/ssl/ca/crl
$ sudo mkdir -p /var/ssl/ca/newcerts
$ sudo chmod 700 /var/ssl/ca/private
$ # シリアル初期化
$ echo "01" | sudo tee -a /var/ssl/ca/serial
$ # インデックス初期化
$ sudo touch /var/ssl/ca/index.txt

CA の鍵と証明書を作成

$ # CA 用秘密鍵作成
$ sudo openssl genrsa -out /var/ssl/ca/private/ca.key 2048
$ # CA 証明書要求作成
$ sudo openssl req -new -key /var/ssl/ca/private/ca.key -out /var/ssl/ca/ca.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:JP
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:oyasirazu.dip.jp
Email Address []:mikoto2000@gmail.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
$ # CA 証明書作成
$ sudo openssl x509 -req -in /var/ssl/ca/ca.csr -signkey /var/ssl/ca/private/ca.key -out /var/ssl/ca/ca.cert
Signature ok
subject=C = JP, ST = Some-State, O = Internet Widgits Pty Ltd, CN = oyasirazu.dip.jp, emailAddress = mikoto2000@gmail.com
Getting Private key

クライアントの鍵と証明書要求を作成

クライアント側でやる作業。

$ # 鍵作成用ディレクトリ作成
$ mkdir keys
$ cd keys
$ # クライアント秘密鍵作成
$ openssl genrsa -out server_01.key 2048
$ # クライアント証明書要求作成
$ openssl req -new -key ./server_01.key -out server_01.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:JP
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:oyasirazu.dip.jp
Email Address []:mikoto2000@gmail.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

クライアント証明書作成

CA 側でやる作業。今回は面倒なので引き続きクライアントように作ったディレクトリの中で実行している。

$ # クライアント証明書作成
$ sudo openssl ca -out server_01.crt -infiles server_01.csr
Using configuration from /usr/lib/ssl/openssl.cnf
Can't open /var/ssl/ca/index.txt.attr for reading, No such file or directory
140386359203072:error:02001002:system library:fopen:No such file or directory:../crypto/bio/bss_file.c:74:fopen('/var/ssl/ca/index.txt.attr','r')
140386359203072:error:2006D080:BIO routines:BIO_new_file:no such file:../crypto/bio/bss_file.c:81:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Dec 12 16:10:51 2017 GMT
            Not After : Dec 12 16:10:51 2018 GMT
        Subject:
            countryName               = JP
            stateOrProvinceName       = Some-State
            organizationName          = Internet Widgits Pty Ltd
            commonName                = oyasirazu.dip.jp
            emailAddress              = mikoto2000@gmail.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                21:94:0F:52:71:1F:5C:7F:47:76:17:C4:75:1F:71:C8:7B:5C:24:98
            X509v3 Authority Key Identifier: 
                DirName:/C=JP/ST=Some-State/O=Internet Widgits Pty Ltd/CN=oyasirazu.dip.jp/emailAddress=mikoto2000@gmail.com
                serial:C9:F2:8A:3D:E2:EB:1B:DE

Certificate is to be certified until Dec 12 16:10:51 2018 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

ここまでにできた server_01.key と server_01.crt を、NGINX settings - GitLab Documentation で指定された場所に突っ込めば HTTPS 接続できるようになっているはず。

Debian9 に Docker をインストールした

基本的に下記ページのコマンドを叩いていくだけ。

Debian9 の公式 apt リポジトリは、docker コマンドがなかったり、 docker-compose が古かったりするみたい。

作業内容

$ sudo apt install apt-transport-https ca-certificates curl gnupg2 software-properties-common
$ curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo "$ID")/gpg | sudo apt-key add -
$ sudo apt-key fingerprint 0EBFCD88
$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/$(. /etc/os-release; echo "$ID") $(lsb_release -cs) stable"
$ sudo apt update
$ sudo apt install docker-ce
$ sudo curl -L https://github.com/docker/compose/releases/download/1.17.0/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
$ sudo chmod +x /usr/local/bin/docker-compose

以上。