Skip to main content

6 posts tagged with "IaC"

View All Tags

· 3 min read
zaxro

在日常運用上,一定會用到很多變數,迴圈,基本上會希望程式語言能做到的事情,在ansible裡也有同樣的實現!

keyword

以下會羅列常用關鍵字:

  • with_items:相當於for迴圈打開list
  • loop:相當於for迴圈打開list(Ansible 2.5 開始已被推薦使用)
- name: Looping using loop (recommended approach)
debug:
msg: "Item: {{ item }}"
loop:
- item1
- item2
- item3
  • loop_control:loop可以配合loop_control做進一步設定,例如設定起始點,取index等動作!
- name: Loop control example
hosts: localhost
vars:
services:
- service1
- service2
- service3
tasks:
- name: Looping over services with custom loop variable name and index
debug:
msg: "Service: {{ custom_service_var }}, Index: {{ my_index }}"
loop: "{{ services }}"
loop_control:
loop_var: custom_service_var
index_var: my_index
  • when: 也就是if的用法
- name: Run a task based on a comparison
command: echo "This task will run if variable is greater than 10"
when: my_variable > 10
  • include 或 include_tasks:用於引用其他的任務文件。
  • import_tasks:用於導入其他的任務文件。
  • tags:用於標記任務,執行ansible-playboook可以指定tags
  • notify:配合handlers在狀態為change時作操作
  • become:用於指定是否切換到超級用戶(root)權限執行任務。
  • become_user: 由root切到哪個user執行,通常配合become一起!

module

以下包含建立變數,做特定事項

  • set_fact: 用於建立變數
- name: Set systemd version fact
set_fact:
node_exporter_systemd_version: "{{ __systemd_version.stdout_lines[0] | regex_replace('^systemd\\s(\\d+).*$', '\\1') }}"
  • register:用於捕獲命令的標準輸出及錯誤輸出然後放到某變數內!
- name: Get systemd version
command: systemctl --version
changed_when: false
check_mode: false
register: __systemd_version
tags:
- skip_ansible_lint
  • assert: 當條件符合會拋錯並終止playbook執行
- name: Check if a variable is greater than 10
assert:
that: my_variable > 10
fail_msg: "my_variable should be greater than 10"
  • file 模組:用於處理文件和目錄,例如創建、刪除、修改權限等操作。
  • find 模組:用於在遠程主機上搜索文件並返回結果。
  • sysctl 模組:用於設置系統內核參數,並在需要時重新載入。
  • stat 模組:用於檢查文件或目錄的狀態,確定它們是否存在以及相關屬性。
  • debug 模組:用於在執行期間輸出訊息,用於調試和檢查變數。
  • block 模組:用於定義一個區塊,其中一part失敗會全部失敗,可以搭配 rescue 和 always 來執行相應操作。

· 3 min read
zaxro

Define the inventory

[filebeat]
10.199.14.[4:8] #change to your ips

playbook

file_beat_install.yml
---
- name: Install Filebeat
hosts: filebeat
become: yes
tasks:
- name: Import Elastic GPG key
rpm_key:
state: present
key: https://packages.elastic.co/GPG-KEY-elasticsearch

- name: Add Elastic repository
yum_repository:
name: elastic-8.x
description: Elastic repository for 8.x packages
baseurl: https://artifacts.elastic.co/packages/8.x/yum
gpgcheck: yes
gpgkey: https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled: yes

- name: Install filebeat
yum:
name: filebeat
state: present

- name: Enable filebeat service
systemd:
name: filebeat
enabled: yes
- name: Write content to /etc/filebeat/ca.crt
ansible.builtin.copy:
dest: /etc/filebeat/ca.crt
content: |
Bag Attributes
friendlyName: ca
localKeyID: "urlocal ID"
subject=/CN=Elasticsearch HTTP CA
issuer=/CN=Elasticsearch HTTP CA
-----BEGIN CERTIFICATE-----
your ca
-----END CERTIFICATE-----
owner: root
group: root
mode: '0644'

playbook command

check the changes,Make sure these chagnes is ok!

ansible-playbook -i hosts file_beat_install.yml --diff --check

Exucutate the command

ansible-playbook -i hosts file_beat_install.yml --diff

小結

以上是直接透過file_beat_install.yml帶入指定hosts,對機器做安裝filebeat.

改成用roles執行

如果是roles配合用site.yml作為接入口,site,yaml如下

/root/Ansible_DG/site.yaml
- hosts: filebeat
gather_facts: True
become: yes
become_user: root
become_method: su
become_exe: sudo su
roles:
- filebeat_install

roles資料夾底下整個結構會變這樣

filebeat_install/       # 角色名
tasks/ # 任务目录
main.yml # 任务定义文件

然後main.yml格式不能照前面的,要改成以下

/root/Ansible_DG/roles/filebeat_install/tasks/main.yml
---
- name: Install necessary packages
apt:
name:
- apt-transport-https
- wget
state: present

- name: Add Elastic GPG key
apt_key:
url: https://artifacts.elastic.co/GPG-KEY-elasticsearch
state: present

- name: Add Elastic repository
apt_repository:
repo: "deb https://artifacts.elastic.co/packages/8.x/apt stable main"
state: present
filename: elastic-8.x

- name: Update apt and install filebeat
apt:
name: filebeat
update_cache: yes
state: present

- name: Enable filebeat service
systemd:
name: filebeat
enabled: yes

- name: Write content to /etc/filebeat/ca.crt
ansible.builtin.copy:
dest: /etc/filebeat/ca.crt
content: |
Bag Attributes
friendlyName: ca
localKeyID: "urlocal ID"
subject=/CN=Elasticsearch HTTP CA
issuer=/CN=Elasticsearch HTTP CA
-----BEGIN CERTIFICATE-----
your ca
-----END CERTIFICATE-----
owner: root
group: root
mode: '0644'

並執行指令

ansible-playbook site.yaml -i hosts --limit filebeat
info

定義hosts有很多方式,在gcp部分因為GCP會自动為每个機器生成这样的内部DNS名稱,ex:[機器名稱].asia-east2-a.c.baseservice-he.internal.所以他在定義ansible那邊其實會比較易懂,可以直接用機器名稱解到IP.

· 13 min read
zaxro

資料夾結構

github位置

.
├── README.md
├── ansible.cfg
├── ansible.log
├── callback_plugins
│   ├── __pycache__
│   │   ├── profile_tasks.cpython-310.pyc
│   │   └── profile_tasks.cpython-39.pyc
│   ├── profile_tasks.py
│   └── profile_tasks.pyc
├── group_vars
│   └── CentOS7.yaml
├── host_vars
│   ├── Centos8.yaml
│   ├── localhost.yaml
│   └── prometheus_server
├── hosts
├── roles
│   ├── docker
│   │   ├── tasks
│   │   │   └── main.yaml
│   │   └── vars
│   │   └── main.yaml
│   ├── nginx
│   │   ├── tasks
│   │   │   └── main.yaml
│   │   └── vars
│   │   └── main.yaml
│   └── ubuntu_base
│   ├── files
│   │   ├── ansible.pub
│   │   └── kaka.pub
│   ├── handlers
│   │   └── main.yml
│   ├── tasks
│   │   └── main.yaml
│   ├── templates
│   │   └── sshd_config.j2
│   └── vars
│   └── main.yaml
├── site.yaml
└── test.yaml
  • 因為檔案太多了,讀的順序會是入口點site.yaml看是使用哪個role
  • roles資料夾底下看對應role,ex ubuntu_base,他底下也有一堆資料夾
  • ubuntu_base資料夾底下看tasks裡面的main.yaml,基本上該role會做的各指令就會在上面
    • tasks裡面會用到的變數要看vars資料夾 or host_vars or group_vars等資料夾,變數有很多層級會依據優先序去拿值!
    • files資料夾會放要複製過去的文件,ex.這邊放的是公鑰,也可以放更新的憑證等
    • templates資料夾也是放要複製到目標主機的文件,跟file資料夾差別是templates裡面放的文件可以透過挖變數把值放入,例如我要設定目標主機的sshd_config,做到吃變數以改ssh port這類操作
    • handlers資料夾裡面放的是當某條件達成後會執行的指令,常常用在設定檔有改動,才會重啟服務的操作.
  • roles結束後,會確認目標主機,這邊是放在hosts文件內(有很多放法,可以參考官方建議best pratices).

執行指令

ansible-playbook -i /path/to/your/inventory site.yml --limit 'yourInstancesGroup'

之後示範是先用這個指令,指定主機跟劇本!

ansible-playbook -i ./hosts site.yaml --limit 'Ubuntu22'

詳細各檔案內容

會以ubuntu為例,之後會寫判斷主機系統!

site.yml

第一個 play 針對 Ubuntu22 主機群組執行。gather_facts: True 表示在運行 play 之前搜集主機的事實。roles 中指定了 ubuntu_base 角色,其他意思差不多,預設情況下,Ansible 會在對應的roles資料夾的 tasks 資料夾中尋找並執行 main.yml 檔案。

site.yml
---
- hosts: Ubuntu22
gather_facts: True
roles:
- ubuntu_base

- hosts: Docker
gather_facts: False
roles:
- docker

- hosts: Nginx
gather_facts: True
roles:
- nginx

roles/ubuntu_base

這邊會用ubuntu_base資料夾做目標,底下tasks做的事情是對系統的基礎操作.ansible_distribution 是 Ansible 的系統事實 (system fact) 之一,它是 Ansible 在目標主機上執行時自動收集的系統相關資訊之一。

roles/ubuntu_base/tasks/main.yaml
# Disable SELinux
- name: diskable SELinux
selinux:
state: disabled
when: ansible_distribution == 'CentOS'


- name: Check if Service Exists
shell: "systemctl -a|grep {{ need_to_stopped_service}}|wc -l"
register: service_exists

- name: Stop service firewalld, if started
ansible.builtin.service:
name: "{{ need_to_stopped_service }}"
state: stopped
enabled: false
when: service_exists|int > 0

- name: Set a hostname
ansible.builtin.hostname:
name: "{{ hostname }}"
become: true

- name: install Base package
apt:
name: "{{ item }}"
state: latest
loop: "{{ base_packages }}"
become: true
# set the TimeZone
- name: Set timezone to Asia/Manila
community.general.timezone:
name: "{{ time_zone }}"
become: true


- name: Set sysctl file limits
#pam_limits: domain='*' limit_type=`item`.`limit_type` limit_item=`item`.`limit_item` value=`item`.`value`
become: true
pam_limits:
dest: "{{ item.dest }}"
domain: '*'
limit_type: "{{ item.limit_type }}"
limit_item: "{{ item.limit_item }}"
value: "{{ item.value }}"
with_items:
- { dest: '/etc/security/limits.conf',limit_type: 'soft',limit_item: 'nofile', value: '655350' }
- { dest: '/etc/security/limits.conf',limit_type: 'hard',limit_item: 'nofile', value: '655350'}
- { dest: '/etc/security/limits.conf',limit_type: 'soft',limit_item: 'nproc', value: '102400' }
- { dest: '/etc/security/limits.conf',limit_type: 'hard',limit_item: 'nproc', value: '102400' }
- { dest: '/etc/security/limits.conf',limit_type: 'soft',limit_item: 'sigpending', value: '255377' }
- { dest: '/etc/security/limits.conf',limit_type: 'hard',limit_item: 'sigpending', value: '255377' }
- { dest: '/etc/security/limits.d/90-nproc.conf', limit_type: 'soft',limit_item: 'nproc', value: '262144' }
- { dest: '/etc/security/limits.d/90-nproc.conf', limit_type: 'hard',limit_item: 'nproc', value: '262144' }
tags:
- setlimits

# add ops group
- name: Ensure group "ops" exists
become: true
ansible.builtin.group:
name: ops
state: present

# add ops user
- name: Add the user 'ops' with a bash shell, appending the group ops
become: true
ansible.builtin.user:
name: ops
shell: /bin/bash
groups: ops
append: yes

# add sudo previleges to the ops user
- name: Config /etc/sudoers
become: true
lineinfile: dest=/etc/sudoers state=present line='{{item}}' validate='visudo -cf %s'
with_items:
- "ops ALL=(ALL) NOPASSWD: ALL"
- "Defaults: ops !requiretty"

- name: Set up multiple authorized keys
become: true
authorized_key:
user: ops
state: present
key: '{{ item }}'
with_file: "{{ ssh_pub_key }}"


# config ssh config
- name: Update sshd configuration safely, avoid locking yourself out
become: true
ansible.builtin.template:
src: sshd_config.j2
dest: /etc/ssh/sshd_config
owner: root
group: root
mode: '0600'
validate: /usr/sbin/sshd -t -f %s
backup: yes
notify:
- (Handler) Restart SSHD Service
tags:
- ssd_config
  • 開頭的條件判斷,ansible_distribution 是用於條件判斷的一部分,以確定 SELinux 禁用任務僅在 CentOS 發行版上執行,在ubuntu不需要操作!

  • 中間的檔案限制, /etc/security/limits.conf 中的 nofile 限制是限制每個進程允許打開的檔案數量./etc/security/limits.conf 中的 nproc 限制是設定單個使用者可啟動的最大進程數量./etc/security/limits.conf 中的 sigpending 限制是設定單個使用者可以等待處理的信號(作業系統和程式互相溝通的機制)數量上限./etc/security/limits.d/90-nproc.conf 中的 nproc 限制也是限制是設定單個使用者可啟動的最大進程數量.會以90-nproc.conf優先,簡言之就是限制以下這幾件事.

    1. 開啟檔案數量
    2. 可以開啟的進程數
    3. 可等待處理的信號數
  • 文尾是告訴他怎麼複製sshd檔案到對面主機,而當一個任務包含了 notify 指令,那麼只有當這個任務的結果是「改變」(change)的時候,對應的 handler 才會被觸發。並且,無論有多少個任務觸發了同一個 handler,在整個 playbook 的運行過程中,那個 handler 都只會被運行一次,並且是在所有的任務都運行完成後。這種模式非常適合於管理那些只需要在配置改變時才需要運行的任務,比如服務的重啟。

roles/ubuntu_base/vars/main.yaml
base_packages:
# - epel-release
- vim
- git
- tree
- lrzsz
- lsof
- net-tools
# - openssl-devel
- wget
# - nc

time_zone: Asia/Manila

ssh_config:
port: 22
disalbe_root_login: False
disalbe_password_login: False


ssh_pub_key:
- files/test.pub

need_to_stopped_service: firewalld

定義挖空的變數,基本上變數順序很多,常用的優先序如下

  1. tasks/var
  2. host_vars
  3. group_vars

他有很多順序,詳細看官網這邊

roles/ubuntu_base/templates/sshd_config.j2
# $OpenBSD: sshd_config,v 1.100 2016/08/15 12:32:04 naddy Exp $

# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/bin:/usr/bin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options override the
# default value.

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
Port {{ ssh_config.port }}
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m


{% if ssh_config.disalbe_root_login %}
PermitRootLogin no
{% else %}
PermitRootLogin yes
{% endif %}

#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile .ssh/authorized_keys

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!

{% if ssh_config.disalbe_password_login %}
PasswordAuthentication no
{% else %}
PasswordAuthentication yes
{% endif %}




#PermitEmptyPasswords no

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes

# GSSAPI options
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
#GSSAPIEnablek5users no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
# WARNING: 'UsePAM no' is not supported in Red Hat Enterprise Linux and may cause several
# problems.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation sandbox
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

# override default of no subsystems
Subsystem sftp /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# PermitTTY no
# ForceCommand cvs server

這邊就是sshd的config,會把變數填入補空!如果相同則不會change!

roles/ubuntu_base/handlers/main.yaml
- name: (Handler) Restart SSHD Service
become: true
service:
name: sshd
state: restarted
enabled: yes

handels底下的yaml會對應tasks裡面某個有設定notify的task,當狀態為change會觸發handler操作,主要用途是用於修改設定檔後的服務重啟,如果設定沒改變就當然不用重啟了.

hosts

hosts
[Ubuntu22]
prometheus_server ansible_host=10.0.0.112

[Ubuntu22:vars]
ansible_user=ubuntu


[CentOS7]
localhost
Centos8

[Docker]
localhost
Centos8

[Nginx]
localhost
Centos8

因為我這邊主要示範對ubnutu部署,所以來看[Ubuntu22],這邊定義主機寫法prometheus_server ansible_host=10.0.0.112是因為方邊辨認,直接用ip看不出來是server用途.要注意的是,如果想要對host直接定義變數值,就需要在host_vars底下做一個對應的prometheus_server文件,這個很重要![Ubuntu22:vars]ansible_user=ubuntu這個是定義ansible連進去的使用者,因為預設會連到root,但有些ssh config是限制root不能連入!

vars

host_vars/prometheus_server
---
test1: value1
ansible_ssh_port: 22
hostname: backend1

這就是前面說的,很重要!要針對特定主機設定變數,你的檔名一定要跟你定義在hosts的相同!ex.host_vars/prometheus_server就會對應到hosts文件內的那行prometheus_server ansible_host=10.0.0.112,如果沒有對到就會沒變數!

group_vars/CentOS7.yaml
---
version: CentOS7

group_vars也是要對應到[group]這樣,跟hosts_vars很像!

檢查指令

你設定完之後,除了直接對主機執行等他跑完看結果,還有其他方式做檢查嗎?

以下指令可以檢查各台主機有吃到的變數

ansible-inventory -i hosts --list

檢查預計改變狀況,同時如果文件有異動,顯示異動情況,帶--check跟--diff

 ansible-playbook -i ./hosts site.yaml --limit 'Ubuntu22' --diff --check

· 24 min read
zaxro

使用 Terraform 首要注意事項

  1. apply 之後看到 destroy 有件數,請立刻停手,並按下中斷,然後去找其他人討論

What is Terraform?

HashiCorp 公司打造的 IaC 工具,使用者透過可閱讀的設定檔以達到版控,重複使用,共享設定,管理本地端(on-premises resources)跟雲端(cloud resources)由低階組件,例如:計算、存儲、網路資源,到高層級組件,例如 DNS record,SAAS 功能等的管理.

基本上,常用的雲服務,他都可以操作,地端機器也可以透過 terraform 管理!他有自己的 config 語言(*tf),透過 tf 檔跟各廠商的 api 做串接,也就是說原本你要創建 instance,要自己去翻 aws 的指令,現在只要知道怎麼設定 tf 檔就好,當 terraform 幫你把東西建立好,會把 response 的資訊寫在一隻 state 檔案!

installation

官網安裝cover 所有用例,以下提供我的 lab 環境的安裝方式,linux centos

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install terraform

因為我這邊 lab 都會用 aws,所以要另外設定 IAM 的相關資訊,請人幫你把你的 key 生出來吧

  1. set the AWS_ACCESS_KEY_ID
export AWS_ACCESS_KEY_ID=
  1. set your secret key.
export AWS_SECRET_ACCESS_KEY=

· 11 min read
zaxro

基本上我學新的工具都會先做幾件事情

  1. 中文 google 搜尋看有哪些資源
  2. 乖乖把官網教學文章看過一遍,以及官網的一些重要的基礎文章看完

基本上都會先看官網文件,如果官網怎麼看都不懂,會用中文的教學文件輔助,還好,terraform 的教學文件很不錯~ 當基本資料學完之後,以我的資質一定還是很不熟,所以接著會做幾件事情

  1. 寫篇文件把基本型態,跟常用方式整理一下(像這篇)
  2. 參考別人的實戰教學
  3. 實作

這邊,每件都很重要,把你懂的事情記錄下來有很多好處

  • 你未來遇到事情可以複習
  • 如果以前觀念錯誤可以改正
  • 要找人討論事情或求教,他可以透過文章先了解你的程度

參考別人實戰經驗可以減少自己踩坑機率!

最後,學東西就是要實作,不實作或導入,那有學跟沒學一樣!

IaC 常見管理項目

一個網路服務的提供,中間會經過許多關卡,這邊大致整理以下:

  1. 軟體開發或者更新
  2. 測試環境部署並測試
  3. 正式環境上線
  4. 監控環境

看幾來步驟很少,但實際上細節很多,而且隨著公司技術程度越高,這些過程會被切得越複雜.

軟體開發或者更新的過程,會被切割成,依據 github flow(每家邏輯不同)對各需求,建立不同分支,RD 的 code 推上來之後,要確保品質會經過測試階段,最後合 code,接下來就是把 code 部署到測試環境部署並測試,測試沒問題就會部署到正式環境.

code 的穩定性那段由 CI 管理,部署過程是 CD,而部署有許多方法,但討論 CD 如何做需要從根本『環境』開使談起,要怎麼選擇你的運算資源這個問題很常見,aws 官方提供的講解如以下

· 21 min read
zaxro

這邊放學習經驗,未來工作中如果發現有其他做法,或者發現觀念有錯,都會滾動式修改,請多多見諒~

what is ansible

ansible 是組態管理工具 Configuration management Tool ,含有自動化工具,配置系統、部署軟件和編排更高級的 IT 任務,例如持續部署或零停機滾動更新.

使用 OpenSSH 去管理機器.支援 Kerberos、LDAP 和其他集中式身份驗證管理系統.

Ansible 是 Python 陣營的組態管理工具,不用幫每台機器 (instance) 預載 agent ,只要有 SSH 和 Python 就可以執行.

官網的資訊很多,對於初學者來說,最重要的是Getting started with Ansible以及其底下到小章節,這邊主要是講基礎觀念!

Ansible concepts

tip

基本上,RD 的習慣會是需要的工具先上網找輪子,找不到的自己寫,IT 人員的習慣就是找輪子,並透過輪子寫好的的設定檔去管理任何事情,所以要習慣查官網資料才行,也要了解一隻程式總共有哪些設定檔,及設定檔可能出現的位置!

環境名詞定義

基本環境需要要有以下幾點

  • 控制節點 (Control node):Ansible 控制主機端,安裝有 Ansible 的系統。您可以在控制節點上執行 Ansible 指令,例如 ansible 或 ansible-inventory,主要透過 openssh 到 Managed node.

  • 被管理節點 (Managed node):Ansible 客戶端,由 Ansible 控制主機端所控制的遠端系統或主機,透過 Control node 以 SSH 方式近來這台機器。

文檔名詞定義

  • 庫存清單 (Inventory):一個按邏輯分類的被管理節點列表。您在控制節點上建立庫存清單,以便描述主機部署情況給 Ansible,舉例來說,你的一個服務可能由多台機器組成,Inventory 方便你一次操作這群機器們.

  • Playbooks: 一個 playbook 可以由一到多個 plays 組成,將管理節點(主機)對應至任務。Playbooks 包含變數、角色和任務的有序列表,

    • Plays: Plays 是 Ansible 執行的主要上下文,這個 playbook 物件將被管理的節點(主機)對應至任務。Play 包含變數、角色和任務的有序列表,可以重複執行。

    • Roles: Roles 是一種有限的可重複使用的 Ansible 工具,可以給多個 playbook 重複用

    • Tasks: 會套用於被管理主機的"操作"。

  • Handlers: Handler 是 Task 的一種特殊形式,只有在先前的 Task 發出"changed"狀態的通知時才會執行。

  • Modules: Ansible 提供的 function

  • Plugins: 插件是擴展 Ansible 核心功能的代碼片段,它們可以控制如何連接到受管節點(連接插件),操作數據(過濾插件)甚至控制控制台中顯示的內容(回調插件)

  • Collections:一種以 Playbook、角色、模組和插件等形式分發 Ansible 內容的格式。您可以通過 Ansible Galaxy 安裝和使用集合。

  • AAP: Ansible 自動化平台的簡稱。這是一種包含企業級功能的產品,並整合了 Ansible 生態系統中的許多工具:ansible-core、awx、galaxyNG 等等。