Jupyter × Ansible環境構築

# 概要
Python学習でJupyterを使っており、ansibleも扱いたい

# 環境構築
## 動作環境

```shell:mac
$ uname -a ; docker --version                    
Darwin uni.local 20.6.0 Darwin Kernel Version 20.6.0: Wed Jun 23 00:26:31 PDT 2021; root:xnu-7195.141.2~5/RELEASE_X86_64 x86_64
Docker version 20.10.13, build a224086
```

```shell:jupyter(ubuntu)
$ python --version
Python 3.9.10

$ jupyter --version
Selected Jupyter core packages...
IPython          : 8.2.0
ipykernel        : 6.11.0
ipywidgets       : 7.7.0
jupyter_client   : 7.2.1
jupyter_core     : 4.9.2
jupyter_server   : 1.16.0
jupyterlab       : 3.3.2
nbclient         : 0.5.13
nbconvert        : 6.4.5
nbformat         : 5.2.0
notebook         : 6.4.10
qtconsole        : 5.3.0
traitlets        : 5.1.1
```

## Ansibleをインストールする
[Installing Ansible on Ubuntu](https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html#latest-releases-via-apt-ubuntu)
aptでインストールする

```:公式手順
$ sudo apt update
$ sudo apt install software-properties-common
$ sudo add-apt-repository --yes --update ppa:ansible/ansible
$ sudo apt install ansible
```

```shell: バージョン確認
$ ansible --version
ansible [core 2.12.1]
  config file = None
  configured module search path = ['/home/jovyan/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /opt/conda/lib/python3.9/site-packages/ansible
  ansible collection location = /home/jovyan/.ansible/collections:/usr/share/ansible/collections
  executable location = /opt/conda/bin/ansible
  python version = 3.9.10 | packaged by conda-forge | (main, Feb  1 2022, 21:24:11) [GCC 9.4.0]
  jinja version = 3.1.1
  libyaml = True
```


pingテストしてみる

```shell:pingテスト
$ ansible localhost -m ping
[WARNING]: No inventory was parsed, only implicit localhost is available
localhost | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
```

簡単にテストしてみる
インベントリ、Playbookを設定
今回はcumulus linuxに対してホスト名を取得して判定するプログラムにする

- 要素
```shell:ファイル確認
$ tree
.
├── inventory
├── playbook
│   └── A01_check_cumulus_status.yml
└── roles
    └── Cumulus
        └── tasks
            └── check_system.yml
```

- Inventory

```:invenroty
[leaf01]
172.17.0.3 ansible_user=root ansible_ssh_pass=xxxx
```

- Playbook
```yml:playbook/A01_check_cumulus_status.yml
---
- name: A01_Check_Status_Cumulus_Linux
  hosts: leaf01
  become: yes
  gather_facts: no
#  connection: local
  environment:
    PYTHONHTTPSVERIFY: 0

  tasks:
    - name: Set Common Vars
      set_fact:
        hostname: "leaf01"

    - name: Check Status
      import_role:
        name: roles/Cumulus
        tasks_from: check_system.yml
```

- Roles
```yml:roles/Cumulus/tasks/check_system.yml
---
- name: Fetch System Status
  command: net show system json
  register: _re

- name: Modify Vars1
  set_fact:
    re: "{{ _re.stdout | from_json }}"

- name: Mpdify Vars2
  set_fact:
    scc_msg: "SUCCESS: Verify hostname"
    err_msg: "ERROR: Hostname is not valid"
    exp_hostname: "{{ hostname }}"
    var_hostname: "{{ re.hostname }}"

- name: Verify Hostname
  fail:
    msg: "{{err_msg}}"  
  when: exp_hostname != var_hostname

- debug: 
    msg: "{{ scc_msg }}"
```

- Ansible実行
オプション v でデバッグを表示させる
詳細レベルは4段階で vvvv まである


```shell:ansible実行
$ ansible-playbook -i inventory playbook/A01_check_cumulus_status.yml 
[WARNING]:  * Failed to parse /home/jovyan/work/ansible/inventory with script plugin: problem running /home/jovyan/work/ansible/inventory --list ([Errno 13]
Permission denied: '/home/jovyan/work/ansible/inventory')
[WARNING]:  * Failed to parse /home/jovyan/work/ansible/inventory with yaml plugin: We were unable to read either as JSON nor YAML, these are the errors we
got from each: JSON: Expecting value: line 1 column 2 (char 1)  Syntax Error while loading YAML.   did not find expected <document start>  The error appears
to be in '/home/jovyan/work/ansible/inventory': line 2, column 1, but may be elsewhere in the file depending on the exact syntax problem.  The offending line
appears to be:  [leaf01] 172.17.0.3 ansible_user=root ansible_ssh_pass=takePassw0rd ^ here
[WARNING]:  * Failed to parse /home/jovyan/work/ansible/inventory with ini plugin: Invalid host pattern 'hostname:' supplied, ending in ':' is not allowed,
this character is reserved to provide a port.
[WARNING]: Unable to parse /home/jovyan/work/ansible/inventory as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [A01_Check_Status_Cumulus_Linux] *************************************************************************************************************************

TASK [Set Common Vars] ****************************************************************************************************************************************
ok: [172.17.0.3]

TASK [Cumulus : Fetch System Status] **************************************************************************************************************************
changed: [172.17.0.3]

TASK [Cumulus : Modify Vars1] *********************************************************************************************************************************
ok: [172.17.0.3]

TASK [Cumulus : Mpdify Vars2] *********************************************************************************************************************************
ok: [172.17.0.3]

TASK [Cumulus : Verify Hostname] ******************************************************************************************************************************
skipping: [172.17.0.3]

TASK [Cumulus : debug] ****************************************************************************************************************************************
ok: [172.17.0.3] => {
    "msg": "SUCCESS: Verify hostname"
}

PLAY RECAP ****************************************************************************************************************************************************
172.17.0.3                 : ok=5    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
```


## Jupyterにansible_kernelをインストールする

ansible_kernelをインストールする

```shell:ansible_kernelインストール
$ pip install ansible-kernel
$ python -m ansible_kernel.install
```

```shell:カーネル確認
$ jupyter kernelspec list
Available kernels:
  ansible    /opt/conda/share/jupyter/kernels/ansible
  python3    /opt/conda/share/jupyter/kernels/python3
```

# Jupyterでplaybook実行
- 実行イメージ
一つのファイルで実行できるのでレビューしやすそう
タスク単位で実行できて分かりやすい

![スクリーンショット 2022-04-06 14.03.21.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/445177/b91a323a-ea9c-5065-b338-f13c10bd00b8.png)

- インベントリ
行頭は #inventory

- Play
行頭は #play

- Tasks
行頭は #task


## pythonとの組み合わせ

registerだけPythonに引き継げるらしい
変数は引き継げなかった
![スクリーンショット 2022-04-06 14.30.07.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/445177/3f90d848-51b6-256c-3c5e-b395ba8e92a7.png)