0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Ansible学習メモ⑤(Kubernetes関連)

Posted at

業務で最近Ansibleを使い始めました。私自身はエンジニア職ではないので普段コーディングをほとんどしないです。少しAnsibleがわかるように学習し始めています。

1. Ansibleを使い、Kubernetes Namespace作成

以下のモジュールを使用:
kubernetes.core.k8s

まず、コレクションのインストール必要

ansible-galaxy collection install kubernetes.core

作成するマニフェストtest.yamlは以下のようです。

---
- name: create ns on kubernetes
  hosts: localhost
  gather_facts: false
  connection: local
  vars:
    project_name: "myapp"
  tasks:
    - name: create namespace
      kubernetes.core.k8s:
        api_version: v1
        kind: Namespace
        name: "{{ project_name }}"
        state: present

マニフェスト実行

ansible-playbook test.yaml

2. Ansibleを使い、Kubernetes Pod作成

以下のモジュールを使用:
kubernetes.core.k8s
まず、コレクションのインストール必要

ansible-galaxy collection install kubernetes.core

PodのYAML定義ファイルmypod.yamlは以下のようです。

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx:1.21.6
    ports:
    - containerPort: 80

作成するマニフェストtest.yamlは以下のようです。

---
- name: k8s demo
  hosts: localhost
  gather_facts: false
  connection: local
  vars:
    myproject: "example"
  tasks:
    - name: create pod
      kubernetes.core.k8s:
        src: mypod.yaml
        namespace: "{{ myproject }}"
        state: present

マニフェストを実行

ansible-playbook test.yaml

Podだけではなくて、service, secret, Volume作成もすべて各リソースのYamlファイルを作成し、AnsibleのsrcパラメータにYamlファイルのパスを設定すれば、Ansibleを使い各リソースのデプロイが可能です。

3. Ansibleを使い、複数YAMLファイルを一括デプロイ

作成するマニフェストtest.yamlは以下のようです。

---
- name: k8s demo
  hosts: localhost
  gather_facts: false
  connection: local
  tasks:
    - name: Apply k8s resource
      kubernetes.core.k8s:
        definition: "{{ lookup('template', '{{ item }}') | from_yaml }}"
     with_fileglob:
        - "./defs/mynamespace.yaml"
        - "./defs/mypod.yaml"
        - "./defs/myservice.yaml"

マニフェストを実行

ansible-playbook test.yaml

感想

個人的な感想ですが、KubernetesやOpenshiftにリソースをデプロイする際わざわざAnsible使用する必要がないかと思います。(便利性や効率性を感じていません)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?