简介
Ansible是一个IT的自动化工具。它可以控制配置管理、临时任务执行、网络自动化、多节点编排、应用部署和云配置。谷歌Kubernetes引擎提供了一个部署、管理和扩展容器化应用的环境。在这篇文章中,我们将展示如何使用Ansible创建GKE集群。
前提条件
- 已启用计费的GCP项目
- GCP服务账户,并附带GKE管理员的角色
- 服务账户的JSON密钥developers.google.com/identity/pr…
- 对Ansible的基本了解
- 在你的系统中安装Ansible
使用Ansible创建GKE集群
GCP模块需要安装request和google-auth两个库。
pip install requests google-auth
文件夹层次结构


GKE集群的Dyanmic变量
---
all:
vars:
# changes according to requirements
zone: us-central1-c
region: us-centeral1
project_id: <project.id> #enter you project id
gcloud_sa_path: "~/gcpserviceaccount.json" # Enter path to you service account json file
gcloud_service_account: "service-account@project-id.iam.gserviceaccount.com"
credential: "{{lookup('env','HOME') }}/{{gcloud_sa_path}}"
#Cluster information
cluster_name: "gkepratice" #Name of the cluster
initial_node_count: 1 #Number of node for cluster
disk_size_gb: 100
disk_type: "pd-ssd" #disk types
machine_type: "e2-medium" #image types
在inventory文件夹下添加上面这个文件gcp.yaml
为K8s集群和节点池创建一个角色
角色让你根据已知的文件结构自动加载相关的变量、文件、任务、处理程序和其他Ansible工件。在你把你的内容归入角色后,你可以很容易地重复使用它们,并与其他用户分享。
为了创建集群和节点池,我们使用了两个Ansible模块
google.cloud.gcp_container_cluster
google.cloud.gcp_container_node_pool
- name: create a cluster
google.cloud.gcp_container_cluster:
name: "{{ cluster_name }}"
initial_node_count: "{{ initial_node_count }}"
location: "{{ zone }}"
network: "{{ network.name }}"
project: "{{ project_id }}"
auth_kind: serviceaccount
service_account_file: "{{ credential }}"
state: present
register: cluster
#create node pool
- name: create a node pool
google.cloud.gcp_container_node_pool:
name: my-pool-{{ cluster_name }}
initial_node_count: "{{ initial_node_count }}"
cluster: "{{ cluster }}"
config:
disk_size_gb: "{{ disk_size_gb }}"
disk_type: "{{ disk_type }}"
machine_type: "{{ machine_type }}"
location: "{{ zone }}"
project: "{{ project_id }}"
auth_kind: serviceaccount
service_account_file: "{{ credential }}"
state: present
在role/kubernets/tasks/main.yml下使用上述代码
为k8s网络创建角色
这是一个可选的部分,如果我们不创建一个网络,它将使我们的集群在默认的网络上。如果你不想创建一个网络,请随意跳过这一部分,在 roles/kubernets/tasks/main.yml中做一个注释网络。
- name: Create network
google.cloud.gcp_compute_network:
name: network-{{cluster_name}}
auto_create_subnetworks: 'true'
project: "{{project_id}}"
auth_kind: serviceaccount
service_account_file: "{{credential}}"
state: present
register: network
创建Kubernetes的playbook
---
- name: create cluster
hosts: localhost
gather_facts: false
environment: #cred for serviceaccount.json
GOOGLE_CREDENTIALS: "{{ credential }}"
roles:
- network
- kubernetes
运行Ansible-playbook来设置GKE
ansible-playbook k8s.yml -i inventory/gcp_value.yaml


结语
在这篇文章中,我们用最少的代码建立了google Kubernetes引擎。我们可以改变变量文件,这样我们就可以用同样的角色在不同的区域用不同的名字启动一个新的集群,使用ansible我们可以建立我们的基础设施。