# Ansibleの導入

**URL:** https://forum.ficusonline.com/t/topic/549
**Category:** Server
**Tags:** kvm, ansible, qemu
**Created:** [2026 年 2 月 5 日午前 2:58 UTC](https://forum.ficusonline.com/t/topic/549 "2026-02-05T02:58:05Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2026 年 2 月 5 日午前 2:58 UTC](https://forum.ficusonline.com/t/topic/549/1 "2026-02-05T02:58:05Z")

</div>

## Ansibleの導入

> **[Getting started with Ansible — Ansible Community Documentation](https://docs.ansible.com/projects/ansible/latest/getting_started/index.html)**

複数のVMを起動したが、各VMのOSやアプリの更新作業をどうするのか？これら一連の更新作業を自動化するツールがAnsibleです。

_1台ずつログインしてコマンドを打つ_ という手間を、1つの操作にまとめられる便利なツールです。

SSH接続によるリモート操作なので、Ansibleをインストールするマシンは何でも構いません。

また、メンテナンス対象の各VMには特別なソフトを入れる必要がありません。SSH接続さえできれば操作可能です。

Ansibleをインストールしたマシンを **Control Node** 、対象となる各VMを **Managed Node** と定義します。

 ![ansible_inv_start](https://forum.ficusonline.com/uploads/default/original/2X/4/4aa41de3479ea96504a38b8cfe02bb86f0501fc8.svg)

* * *

インストール（Ubuntu24.04）

```shell
$ sudo apt update
$ sudo apt install software-properties-common
$ sudo add-apt-repository --yes --update ppa:ansible/ansible
$ sudo apt install ansible

```

* * *

動作試験フロー

```shell
$ mkdir ansible
$ cd ansible

```

inventory登録（対象VMを指定）ファイル

`hosts.ini`

```auto
[vms]
vm-01 ansible_host=vm-01 ansible_user=ansible
vm-02 ansible_host=vm-02 ansible_user=ansible

```

初回アクセスのため各VMの公開鍵を取得

```shell
ssh-keyscan -H vm-02-ubuntu24 vm-02-debian13 >> ~/.ssh/known_hosts

```

通信確認

```shell
$ ansible -i hosts.ini vms -m ping

```

またはSSHパスワードを入力する場合: -k

```shell
$ ansible -i hosts.ini vms -m ping -k

```

```auto
vm-01 SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3.13"
    },
    "changed": false,
    "ping": "pong"
}
 vm-02 SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3.12"
    },
    "changed": false,
    "ping": "pong"
}

```

Playbookの作成：VM内での具体的な実行命令

#### Nginxのインストール

`setup.yaml`

```auto
- hosts: vms
  become: true
  tasks:
    - name: Install nginx
      apt:
        name: nginx
        state: present
        update_cache: true

```

#### qemu-guest-agentのインストール

`qemu-ga.yaml`

```auto
- hosts: vms
  become: true
  tasks:
    - name: Install qemu-guest-agent
      apt:
        name: qemu-guest-agent
        state: present
        update_cache: true

    - name: Enable qemu-guest-agent service
      systemd:
        name: qemu-guest-agent
        enabled: true

    - name: Start qemu-guest-agent service
      systemd:
        name: qemu-guest-agent
        state: started

```

Playbook適用

```shell
$ ansible-playbook -i hosts.ini setup.yaml

```

```shell
$ ansible-playbook -i hosts.ini qwmu-ga.yaml

```

VMにパスワード入力が必要なVMが含まれている場合

[-K, --ask-become-pass](https://docs.ansible.com/projects/ansible/latest/cli/ansible-console.html#cmdoption-ansible-console-K)

```shell
$ ansible-playbook -i hosts.ini update_upgrade.yaml --ask-become-pass

```

> `ask-pass`と`ask-become-pass`の違い
> 
> | オプション | 用途 | パスワードの種類 |
> | --- | --- | --- |
> | `--ask-pass` (`-k`) | SSH接続時のパスワード | SSHログインパスワード |
> | `--ask-become-pass` (`-K`) | sudo実行時のパスワード | sudoパスワード |

InventoryとPlaybookの組合せで、複数のVMをグループ分けし、アプリをインストールすることも可能です。

* * *

## コレクション

名前空間付きの命令セットなどの機能拡張プラグイン。Playbookでは`apt,systemd`などの一般的な命令（これらもモジュールというプラグイン）は名前空間`ansible.builtin`が省略されています。

### コレクション一覧

> **[Collection Index — Ansible Community Documentation](https://docs.ansible.com/projects/ansible/latest/collections/index.html)**

#### Ansible.Builtin

> **[known\_hosts - Ansible.Builtin — Ansible Community Documentation](https://docs.ansible.com/projects/ansible/latest/collections/ansible/builtin/index.html#plugin-index)**
>
> Collection version 2.20.5.post0

コマンドで確認

```shell
$ ansible-galaxy collection list

```

コレクションリストから特定の名前空間のプラグインをリストアップ

```shell
$ ansible-doc -l | grep ansible.builtin
ansible.builtin.add_host Add a host (and alternativel...                       
ansible.builtin.apt ...                                                   
ansible.builtin.apt_key ...                                                   
ansible.builtin.apt_repository ...                                                   
ansible.builtin.assemble ...                                                   
ansible.builtin.assert ...                                                   
ansible.builtin.async_status ...                                                   
ansible.builtin.blockinfile Insert...                                             
ansible.builtin.command ...                                                   
ansible.builtin.copy ...                                                   
ansible.builtin.cron ...                                                   
ansible.builtin.deb822_repository ...                                                   
ansible.builtin.debconf ...                                                   
ansible.builtin.debug ...                                                   
ansible.builtin.dnf ...                                                   
ansible.builtin.dnf5 ...                                                   
ansible.builtin.dpkg_selections ...                                                   
ansible.builtin.expect ...                                                   
ansible.builtin.fail ...                                                   
ansible.builtin.fetch ...                                                   
ansible.builtin.file ...                                                   
ansible.builtin.find ...                                                   
ansible.builtin.gather_facts ...                                                   
ansible.builtin.get_url ...                                                   
ansible.builtin.getent ...                                                   
ansible.builtin.git ...                                                   
ansible.builtin.group ...                                                   
ansible.builtin.group_by ...                                                   
ansible.builtin.hostname              
.....
.....
.....

```

プラグイン(`apt`)の詳細

```shell
$ ansible-doc ansible.builtin.apt
> MODULE ansible.builtin.apt (/usr/lib/python3/dist-packages/ansible/modules/apt.py)

  Manages apt packages (such as for Debian/Ubuntu).

OPTIONS (red indicates it is required):

   allow_change_held_packages Allows changing the version of a package which is on the apt hold list.
        default: 'no'
        type: bool

   allow_downgrade Corresponds to the `--allow-downgrades' option for apt.
                    This option enables the named package and version to replace an already installed higher version of that package.
                    Note that setting `allow_downgrade=true' can make this module behave in a non-idempotent way.
                    (The task could end up with a set of packages that does not match the complete list of specified packages to install).
                    `allow_downgrade' is only supported by `apt' and will be ignored if `aptitude' is detected or specified.
        aliases: [allow-downgrade, allow_downgrades, allow-downgrades]
        default: 'no'
        type: bool
.....
.....
.....

```

* * *

### 補足

#### 特定のグループだけ実行: --limit オプション

Inventoryファイルでグループ分けしたホストに適用

```auto
$ ansible-playbook -i hosts.ini update_all_vms.yml --limit vms_debian

```

#### 接続先SSH公開キーの取得

未登録の場合エラーとなるため、下記コマンドで登録するか、一度SSHでログインする際に手続きする必要があります。

```auto
$ ssh-keyscan -H vm-01 vm-02 vm-03 >> ~/.ssh/known_hosts

```

* * *

### コマンドラインツール

> **[Using Ansible command line tools — Ansible Community Documentation](https://docs.ansible.com/projects/ansible/latest/command_guide/index.html)**

- [ansible](https://docs.ansible.com/projects/ansible/latest/cli/ansible.html)
- [ansible-config](https://docs.ansible.com/projects/ansible/latest/cli/ansible-config.html)
- [ansible-console](https://docs.ansible.com/projects/ansible/latest/cli/ansible-console.html)
- [ansible-doc](https://docs.ansible.com/projects/ansible/latest/cli/ansible-doc.html)
- [ansible-galaxy](https://docs.ansible.com/projects/ansible/latest/cli/ansible-galaxy.html)
- [ansible-inventory](https://docs.ansible.com/projects/ansible/latest/cli/ansible-inventory.html)
- [ansible-playbook](https://docs.ansible.com/projects/ansible/latest/cli/ansible-playbook.html)
- [ansible-pull](https://docs.ansible.com/projects/ansible/latest/cli/ansible-pull.html)
- [ansible-vault](https://docs.ansible.com/projects/ansible/latest/cli/ansible-vault.html)

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2026 年 5 月 5 日午前 2:27 UTC](https://forum.ficusonline.com/t/topic/549/2 "2026-05-05T02:27:22Z")

</div>

## マジック変数

ドキュメント

> **[environment - Discovering variables: facts and magic variables — Ansible...](https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_vars_facts.html#information-about-ansible-magic-variables)**
>
> With Ansible you can retrieve or discover certain variables containing information about your remote systems or about Ansible itself. Variables related to remote systems are called facts. With facts, you can use the behavior or state of one system as...

変数一覧

> **[Special Variables — Ansible Community Documentation](https://docs.ansible.com/projects/ansible/latest/reference_appendices/special_variables.html)**

#### 使用例

```yaml
# inventory
hypervisor01.example.com ansible_host=192.168.1.10

```

```yaml
inventory_hostname # → "hypervisor01.example.com"
inventory_hostname_short # → "hypervisor01"
ansible_host # → "192.168.1.10"
ansible_hostname # → OSのhostname設定値（例: "hypervisor01"）
ansible_fqdn # → OSのFQDN設定値（例: "hypervisor01.example.com"）

```

#### 変数記述ルール

> **[Using variables — Ansible Community Documentation](https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_variables.html)**

#### Ansible facts

Ansibleが接続先ホストから **自動収集するシステム情報**

> **[Discovering variables: facts and magic variables — Ansible Community...](https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_vars_facts.html)**

- 
#### 収集される情報の例

```yaml
ansible_facts
├── os_family # → "Debian"
├── distribution # → "Ubuntu"
├── distribution_version # → "24.04"
├── hostname # → "optiplex-3060"
├── fqdn # → "optiplex-3060.local"
├── default_ipv4
│ └── address # → "192.168.1.10"
├── memory_mb
│ └── real
│ └── total # → "16384"
├── processor # → CPUの情報
├── env
│ ├── HOME # → "/home/takanobu"
│ └── USER # → "takanobu"
└── mounts # → マウント情報

```

```sh
# 全factsを表示
$ ansible kvm_hosts -i hosts.ini -m setup

# 特定の情報だけ表示
$ ansible kvm_hosts -i hosts.ini -m setup -a "filter=ansible_distribution*"

```
