隨著雲端服務的普及,自動化管理雲端資源變得至關重要。本文將介紹如何使用 Ansible 管理 AWS、GCP 和 Azure 上的虛擬機器,涵蓋從安裝必要套件、設定身份驗證到建立和組態虛擬機器的完整流程。透過 Ansible 的自動化能力,可以有效簡化跨雲平台的資源管理,提升效率並降低人為錯誤的風險。同時,文章也提供 Playbook 範例和程式碼解析,幫助讀者快速理解和應用 Ansible 在雲端環境中的實務操作。

自動化雲端管理:AWS 與 Google Cloud Platform 的實戰

隨著雲端運算的普及,企業越來越依賴雲端供應商來滿足其運算需求。Amazon Web Services(AWS)作為最大的雲端供應商之一,其重要性不言而喻。本篇文章將介紹如何使用 Ansible 自動化 AWS 環境的設定和管理,並進一步探討如何將自動化擴充套件到 Google Cloud Platform(GCP)。

自動化 AWS 環境設定

要使用 Ansible 自動化 AWS 環境,首先需要安裝 boto 函式庫。boto 是 AWS 的 Python SDK,能夠讓 Ansible 與 AWS 服務進行互動。

安裝 boto

執行以下指令安裝 boto

$ pip install boto

設定身份驗證

boto 會從 ~/.aws/credentials 檔案中讀取必要的憑證。有兩種方法可以設定這個檔案:使用 AWS CLI 工具或手動編輯檔案。

手動設定 ~/.aws/credentials 檔案的範例如下:

[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY

建立第一個 AWS 虛擬機器

建立一個名為 aws.yaml 的 Playbook,內容如下:

---
- hosts: localhost
  tasks:
    - name: 確保 SSH 金鑰對存在
      ec2_key:
        name: fale
        key_material: "{{ lookup('file', '~/.ssh/fale.pub') }}"

    - name: 收集 EC2 VPC 網路資訊
      ec2_vpc_net_facts:
        region: eu-west-1
      register: aws_simple_net

    - name: 收集 EC2 VPC 子網路資訊
      ec2_vpc_subnet_facts:
        region: eu-west-1
        filters:
          vpc-id: '{{ aws_simple_net.vpcs.0.id }}'
      register: aws_simple_subnet

    - name: 確保 wssg 安全群組存在
      ec2_group:
        name: wssg
        description: Web Security Group
        region: eu-west-1
        vpc_id: '{{ aws_simple_net.vpcs.0.id }}'
        rules:
          - proto: tcp
            from_port: 22
            to_port: 22
            cidr_ip: 0.0.0.0/0
          - proto: tcp
            from_port: 80
            to_port: 80
            cidr_ip: 0.0.0.0/0
          - proto: tcp
            from_port: 443
            to_port: 443
            cidr_ip: 0.0.0.0/0
        rules_egress:
          - proto: all
            cidr_ip: 0.0.0.0/0
      register: aws_simple_wssg

    - name: 建立虛擬機器
      ec2:
        assign_public_ip: true
        image: ami-3548444c
        region: eu-west-1
        exact_count: 1
        key_name: fale
        count_tag:
          Name: ws01.ansible2cookbook.com
        instance_tags:
          Name: ws01.ansible2cookbook.com
        instance_type: t2.micro
        group_id: '{{ aws_simple_wssg.group_id }}'
        vpc_subnet_id: '{{ aws_simple_subnet.subnets.0.id }}'
        volumes:
          - device_name: /dev/sda1
            volume_type: gp2
            volume_size: 10
            delete_on_termination: True

執行 Playbook:

$ ansible-playbook aws.yaml

程式碼解析

  1. 確保 SSH 金鑰對存在:使用 ec2_key 模組上傳 SSH 公鑰到 AWS。

    • 解說:此步驟確保 Ansible 可以透過 SSH 連線到新建立的虛擬機器。
  2. 收集 EC2 VPC 網路和子網路資訊:使用 ec2_vpc_net_factsec2_vpc_subnet_facts 模組查詢 VPC 和子網路的 ID。

    • 解說:這兩個步驟是為了取得 VPC 和子網路的 ID,以便後續步驟使用。
  3. 建立安全群組:使用 ec2_group 模組建立一個允許特定流量(SSH、HTTP、HTTPS)的安全群組。

    • 解說:此步驟確保虛擬機器有適當的安全群組規則,允許必要的流量透過。
  4. 建立虛擬機器:使用 ec2 模組建立一個新的 EC2 例項。

    • 解說:此步驟綜合利用前面的步驟中收集的資訊,建立一個組態完整的虛擬機器。

自動化 Google Cloud Platform

與 AWS 類別似,使用 Ansible 自動化 GCP 也需要安裝特定的 Python 模組,包括 requestsgoogle-auth

安裝必要模組

執行以下指令安裝必要模組:

$ pip install requests google-auth

身份驗證

GCP 提供兩種身份驗證方法:Service Account 和 Machine Account。建議使用 Service Account,因為它更靈活且適用於大多數情況。

使用 Service Account
  1. 建立 Service Account 並下載金鑰檔案。
  2. 設定以下環境變數:
    • GCP_AUTH_KIND
    • GCP_SERVICE_ACCOUNT_EMAIL
    • GCP_SERVICE_ACCOUNT_FILE
    • GCP_SCOPES

這樣,Ansible 就能夠使用 Service Account 認證與 GCP API 互動。

使用Ansible管理雲端資源:GCP與Azure例項建立

前言

在現代化的雲端運算環境中,自動化管理雲端資源已成為企業的重要需求。Ansible作為一款強大的自動化工具,能夠簡化跨雲平台的資源管理作業。本文將探討如何使用Ansible建立和管理Google Cloud Platform(GCP)及Microsoft Azure上的虛擬機器例項。

在GCP上建立第一台虛擬機器

建立GCE虛擬機器的Playbook

首先,我們需要在GCP上建立一台虛擬機器。為此,我們將建立一個名為gce.yaml的Ansible Playbook:

---
- hosts: localhost
  tasks:
    - name: 建立GCP例項
      gcp_compute_instance:
        name: TestMachine
        machine_type: n1-standard-1
        disks:
          - auto_delete: 'true'
            boot: 'true'
            initialize_params:
              source_image: family/centos-7
              disk_size_gb: 10
        zone: eu-west1-c
        auth_kind: serviceaccount
        service_account_file: "~/sa.json"
        state: present

執行Playbook

執行以下命令來執行Playbook:

$ ansible-playbook gce.yaml

結果解析

執行結果將顯示類別似以下的輸出:

PLAY [localhost] *******************************************************************
***************
TASK [Gathering Facts] *******************************************************************
*********
ok: [localhost]
TASK [建立GCP例項] *******************************************************************
*******
changed: [localhost]
PLAY RECAP *******************************************************************
*********************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

#### 內容解密:

  1. gcp_compute_instance模組:用於在GCP上建立虛擬機器例項。
  2. name引數:指定虛擬機器的名稱為TestMachine
  3. machine_type引數:選擇虛擬機器的型別為n1-standard-1
  4. disks組態:設定虛擬機器的磁碟引數,包括自動刪除、啟動磁碟和初始化引數。
  5. zone引數:指定虛擬機器所在的區域為eu-west1-c
  6. auth_kindservice_account_file:用於驗證與GCP的連線,使用服務帳戶進行身份驗證。

無縫整合Azure自動化

安裝Azure SDK for Python

要讓Ansible管理Azure雲端資源,首先需要安裝Azure SDK for Python:

$ pip install 'ansible[azure]'

設定Azure驗證

Ansible支援多種方式驗證Azure帳戶,主要透過~/.azure/credentials檔案進行組態。以下是三種常見的驗證組態方法:

  1. 使用主體憑證
[default]
subscription_id = [YOUR_SUBSCRIPTION_ID_HERE]
client_id = [YOUR_CLIENT_ID_HERE]
secret = [YOUR_SECRET_HERE]
tenant = [YOUR_TENANT_HERE]
  1. 使用Active Directory使用者名稱和密碼
[default]
ad_user = [YOUR_AD_USER_HERE]
password = [YOUR_AD_PASSWORD_HERE]
  1. 使用Active Directory登入與ADFS
[default]
ad_user = [YOUR_AD_USER_HERE]
password = [YOUR_AD_PASSWORD_HERE]
client_id = [YOUR_CLIENT_ID_HERE]
tenant = [YOUR_TENANT_HERE]
adfs_authority_url = [YOUR_ADFS_AUTHORITY_URL_HERE]

在Azure上建立第一台虛擬機器

建立Azure虛擬機器的Playbook

建立一個名為azure.yaml的Playbook:

---
- hosts: localhost
  tasks:
    - name: 確保儲存帳戶存在
      azure_rm_storageaccount:
        resource_group: Testing
        name: mysa
        account_type: Standard_LRS
    
    - name: 確保虛擬網路存在
      azure_rm_virtualnetwork:
        resource_group: Testing
        name: myvn
        address_prefixes: "10.10.0.0/16"
    
    - name: 確保子網路存在
      azure_rm_subnet:
        resource_group: Testing
        name: mysn
        address_prefix: "10.10.0.0/24"
        virtual_network: myvn
    
    - name: 確保公有IP存在
      azure_rm_publicipaddress:
        resource_group: Testing
        allocation_method: Static
        name: myip
    
    - name: 確保安全群組允許SSH連線
      azure_rm_securitygroup:
        resource_group: Testing
        name: mysg
        rules:
          - name: SSH
            protocol: Tcp
            destination_port_range: 22
            access: Allow
            priority: 101
            direction: Inbound
    
    - name: 確保網路介面存在
      azure_rm_networkinterface:
        resource_group: Testing
        name: testnic001
        virtual_network: myvn
        subnet: mysn
        public_ip_name: myip
        security_group: mysg
    
    - name: 確保虛擬機器存在
      azure_rm_virtualmachine:
        resource_group: Testing
        name: myvm01
        vm_size: Standard_D1
        storage_account: mysa
        storage_container: myvm01
        storage_blob: myvm01.vhd
        admin_username: admin
        admin_password: Password!
        network_interfaces: testnic001
        image:
          offer: CentOS
          publisher: OpenLogic
          sku: '8.0'
          version: latest
執行Azure Playbook
$ ansible-playbook azure.yaml

#### 內容解密:

  1. azure_rm_storageaccount模組:建立Azure儲存帳戶。
  2. azure_rm_virtualnetworkazure_rm_subnet模組:建立虛擬網路和子網路。
  3. azure_rm_publicipaddress模組:分配公有IP。
  4. azure_rm_securitygroup模組:設定安全群組規則,允許SSH連線。
  5. azure_rm_networkinterface模組:建立網路介面並關聯公有IP和安全群組。
  6. azure_rm_virtualmachine模組:建立虛擬機器並組態相關引數。

使用Ansible管理雲端資源

隨著雲端運算的普及,企業對於雲端資源的管理需求日益增加。Ansible作為一種自動化工具,可以幫助企業簡化雲端資源的管理流程。本文將介紹如何使用Ansible管理Azure、Rackspace Cloud和OpenStack等雲端資源。

管理Azure雲端資源

Azure是微軟提供的雲端運算平台,提供了豐富的雲端服務。要使用Ansible管理Azure資源,首先需要安裝azure模組。

安裝azure模組

$ pip install azure

建立Azure資源

建立Azure資源需要先建立多個相關資源,如Storage Account、Virtual Network、Subnet、Public IP、Security Group和NIC等。以下是一個範例的Playbook:

---
- hosts: localhost
  tasks:
  - name: Ensure the Storage Account is present
    azure_rm_storageaccount:
      resource_group: myResourceGroup
      name: mystorageaccount
      account_type: Standard_LRS

  - name: Ensure the Virtual Network is present
    azure_rm_virtualnetwork:
      resource_group: myResourceGroup
      name: myVirtualNetwork
      address_prefixes: "10.0.0.0/16"

  - name: Ensure the Subnet is present
    azure_rm_subnet:
      resource_group: myResourceGroup
      name: mySubnet
      address_prefix: "10.0.1.0/24"
      virtual_network: myVirtualNetwork

  - name: Ensure the Public IP is present
    azure_rm_publicipaddress:
      resource_group: myResourceGroup
      allocation_method: Static
      name: myPublicIP

  - name: Ensure the Security Group is present
    azure_rm_securitygroup:
      resource_group: myResourceGroup
      name: mySecurityGroup
      rules:
        - name: SSH
          protocol: Tcp
          destination_port_range: 22
          access: Allow
          priority: 1001
          direction: Inbound

  - name: Ensure the NIC is present
    azure_rm_networkinterface:
      resource_group: myResourceGroup
      name: myNIC
      virtual_network: myVirtualNetwork
      subnet_name: mySubnet
      public_ip_name: myPublicIP
      security_group: mySecurityGroup

  - name: Ensure the Virtual Machine is present
    azure_rm_virtualmachine:
      resource_group: myResourceGroup
      name: myVM
      vm_size: Standard_DS1_v2
      admin_username: azureuser
      admin_password: AzureUser123456!
      network_interfaces: myNIC
      image:
        offer: CentOS
        publisher: OpenLogic
        sku: '8.1'
        version: latest

執行Playbook

$ ansible-playbook azure.yaml

管理Rackspace Cloud資源

Rackspace Cloud是Rackspace提供的雲端運算平台。要使用Ansible管理Rackspace Cloud資源,首先需要安裝pyrax模組。

安裝pyrax模組

$ pip install pyrax

設定Rackspace Cloud憑證

建立一個檔案~/.rackspace_credentials,內容如下:

[rackspace_cloud]
username = YOUR_USERNAME_HERE
api_key = YOUR_API_KEY_HERE

然後設定環境變數:

$ export RAX_CREDS_FILE=~/.rackspace_credentials

建立Rackspace Cloud資源

以下是一個範例的Playbook:

---
- hosts: localhost
  tasks:
  - name: Ensure the my_machine exists
    rax:
      name: my_machine
      flavor: 4
      image: centos-8
      count: 1
      group: my_group
      wait: True

執行Playbook

$ ansible-playbook rax.yaml

管理OpenStack資源

OpenStack是一個開源的雲端運算平台。要使用Ansible管理OpenStack資源,首先需要安裝openstacksdk模組。

安裝openstacksdk模組

$ pip install openstacksdk

設定OpenStack憑證

建立一個檔案~/.config/openstack/clouds.yaml,內容如下:

clouds:
  test_cloud:
    region_name: MyRegion
    auth:
      auth_url: http://YOUR_AUTH_URL_HERE:5000/v2.0/
      username: YOUR_USERNAME_HERE
      password: YOUR_PASSWORD_HERE
      project_name: myProject

建立OpenStack資源

以下是一個範例的Playbook:

---
- hosts: localhost
  tasks:
  - name: Ensure the SSH key is present on OpenStack
    os_keypair:
      state: present
      name: ansible_key
      public_key_file: "{{ '~' | expanduser }}/.ssh/id_rsa.pub"

  - name: Ensure we have a CentOS image
    get_url:
      url: http://cloud.centos.org/centos/8/x86_64/images/CentOS-8-GenericCloud-8.1.1911-20200113.3.x86_64.qcow2
      dest: /tmp/CentOS-8-GenericCloud-8.1.1911-20200113.3.x86_64.qcow2

  - name: Ensure the CentOS image is in OpenStack
    os_image:
      name: centos
      container_format: bare
      disk_format: qcow2
      state: present
      filename: /tmp/CentOS-8-GenericCloud-8.1.1911-20200113.3.x86_64.qcow2

執行Playbook

$ ansible-playbook openstack.yaml
內容解密:

本文介紹瞭如何使用Ansible管理多種雲端資源,包括Azure、Rackspace Cloud和OpenStack。首先,需要安裝相應的模組,如azurepyraxopenstacksdk。然後,需要設定憑證,如建立~/.rackspace_credentials檔案和設定環境變數。接著,可以使用Ansible的Playbook來建立和管理雲端資源,如建立虛擬機器、網路和安全群組等。最後,執行Playbook即可完成雲端資源的建立和管理。透過這些步驟,可以簡化雲端資源的管理流程,提高管理的效率和準確性。