Skip to content

Instantly share code, notes, and snippets.

@Akkiesoft
Created December 11, 2022 05:34
Show Gist options
  • Save Akkiesoft/a85326984bfe2191c1448307fd189303 to your computer and use it in GitHub Desktop.
Save Akkiesoft/a85326984bfe2191c1448307fd189303 to your computer and use it in GitHub Desktop.
Ansible快速指南

Ansible にゅうもん

いるもの

  • Ansible実行環境
    • この手順ではRockyLinux 8を使用
  • 構築対象のサーバー
    • この手順ではRockyLinux 8を使用

事前準備

  • やらない場合はAnsibleのオプションで対応できるけど、やったほうが良く、この手順も準備済みであることを想定する

  • Ansible実行環境から構築対象のサーバーに公開鍵認証でSSHログインできるようにする

    • SSHホスト鍵登録は事前に済ませる
  • 構築対象のサーバーでsudoでコマンド実行時にパスワードが聞かれないようにsudoersを設定する

    • 一般ユーザーでなくrootユーザーで作業しているなら無視
    $ sudo visudo
    
    # 以下を追記(rockyは自分のユーザー名)
    rocky   ALL=(ALL)       NOPASSWD: ALL
    

Ansible実行環境にAnsibleをインストール

$ sudo dnf install ansible-core
$ ansible-galaxy collection install ansible.posix
  • ※ansible.posixはfirewalldモジュールの実行に必要

Ansible実行環境でPlaybookを書く

  • httpd.yml
- hosts: websv
  # AnsibleがOSの情報を収集するのをスキップする。
  # PlaybookでOS情報を使うときはスキップしない
  gather_facts: no
  # becomeはタスク単位でもPlaybook単位でも記述できる
  become: yes
  # タスク
  tasks:
    # SELinuxをPermissiveにして、変更された場合はOSを再起動する
    - name: put selinux in permissive mode
      selinux:
        policy: targeted
        state: permissive
      notify: reboot os
    - name: reboot if selinux config is changed
      meta: flush_handlers

    # httpdとfirewalldをインストールする
    - name: install httpd, firewalld
      dnf:
        name:
          - httpd
          - firewalld
          - python3-firewall
        # presentは、インストールされていれば最新じゃなくてもOKとなる
        # latestにして常に最新にしたり、バージョン固定もできる
        state: present

    # httpdとfirewalldを起動して、自動起動も有効にする
    - name: enable and start services
      systemd:
        name: "{{ item }}"
        enabled: yes
        state: started
      loop:
        - httpd
        - firewalld

    # httpポートとhttpsポートを開放する
    - name: configure firewall that allow services for public
      firewalld:
        zone: public
        service: "{{ item }}"
        permanent: true
        state: enabled
      loop:
        - http
        - https

    # cockpitがデフォルトで許可されているので止める
    - name: configure firewall that remove allowed default services for public
      firewalld:
        zone: public
        service: "{{ item }}"
        permanent: true
        state: disabled
      loop:
        - cockpit

  # タスクでOS再起動を実行する時に呼ばれるタスク
  handlers:
    - name: reboot os
      reboot:
  • hostsファイル
[websv]
(構築対象のサーバーのIPアドレス)

Ansible実行環境でPlaybookを実行

  • 実行して、いろいろchangedになることを確認する
$ ansible-playbook -i hosts websv.yml -D
  • もう一度実行して、changedがないことを確認する
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment