文章 94
评论 0
浏览 457436
ansible之k8s模块

ansible之k8s模块

一、模块安装

这里使用centos7进行说明。

yum install python2-kubernetes python-openshift ansible

验证

ansible-doc k8s

二、模块使用详解

前提:需要在主机安装kubectl命令并且可以正常执行连接集群

2.1 k8s模块

可以用来创建删除k8s中各种资源

注意:模块具有幂等性,如果监测到资源以及存在则不会进行创建,判断依据为是否有这个相同名称的资源。如果资源内容进行修改资源存在不会进行更新。

1.直接创建

- hosts: localhost
  tasks:
    - name: create namespace
      k8s:   #使用k8s模块
        kubeconfig: /root/.kube/config  #k8s连接的认证文件,如果不指定默认值为~/.kube/config
        name: zhangzhuo  #创建资源名称
        api_version: v1  #资源的api
        kind: Namespace  #资源类型
        state: present   #动作创建present,删除absent

2.使用definition进行创建资源

definition下面直接编写k8s资源yaml文件即可

#直接在文件中定义资源,只能定义一个资源
- hosts: localhost
  tasks:
    - name: create svc
      k8s:
        state: present
        definition:
          apiVersion: v1
          kind: Service
          metadata:
            labels:
              app: service
            name: service
            namespace: zhangzhuo
          spec:
            ports:
            - port: 80
              name: low
              protocol: TCP
              targetPort: 8080
            selector:
              app: service
#从资源文件进行创建,可以在文件中定义多个资源,如果文件进行了变动会自动执行更新操作
- hosts: localhost
  tasks:
    - name: create to file
      k8s:
        state: present
        definition: "{{ lookup('file', '/root/kubernetes/definition/files/definition-file.yaml') }}"
#从template进行创建,与文件类似,但是文件会先进行渲染之后在执行,可使用j2语句进行提前处理
- hosts: localhost
  tasks:
    - name: create to template
      k8s:
        state: present
        definition: "{{ lookup('template', '/root/kubernetes/definition/templates/definition-file.yaml.j2') }}"

3.使用src进行创建

直接使用资源文件进行创建,与definition的file类似。也可定义多个资源,如果改动后资源文件后重复执行会进行更新操作。

- hosts: localhost
  tasks:
    - name: create to src
      k8s:
        state: present
        src: /root/kubernetes/definition/files/definition-file.yaml

2.2 k8s_scale模块

与kubectl scale命令功能类似

#文件中直接编写
- hosts: localhost
  tasks:
    - name: deploy scale
      k8s_scale:  #模块名称
        api_version: apps/v1  #资源api
        namespace: zhangzhuo  #命名空间 
        name: "ceshi"         #资源名称
        kind: Deployment      #资源类型,可设置Deployment,ReplicaSet,Replication Controller, Job
        replicas: "3"         #设置副本集大小
        wait: false           #追踪状态关闭,centos开启会报错。
#使用资源文件,会自动识别资源文件中可配置的资源进行修改
- hosts: localhost
  tasks:
    - name: deploy scale
      k8s_scale:
        src: /root/kubernetes/definition/files/definition-file.yaml
        replicas: 1
        wait: no

2.3 k8s_info模块

与kubectl get命令功能相近

- hosts: localhost
  tasks:
    - name: auth k8s
      k8s_info:
        kind: Pod  #查看资源类型
        name: ceho  #资源名称,不写匹配到的全部
        namespace: zhangzhuo #命名空间
        label_selectors:   #匹配标签
          - app = web
          - tier in (dev, test)
        field_selectors:  #匹配资源某个字段
          - status.phase=Running

标题:ansible之k8s模块
作者:Carey
地址:HTTPS://zhangzhuo.ltd/articles/2023/02/02/1675323487297.html

生而为人

取消