【mac】ansible安裝及基礎使用

YatHo發表於2017-09-06

安裝

環境釋放
  mac  10.12.5

#more /System/Library/CoreServices/SystemVersion.plist

安裝命令

#ruby -e "$(curl --insecure -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
#brew update
#brew install Ansible

安裝後hosts預設訪問位置

/usr/local/etc/ansible/hosts

公私鑰配置

建立公私鑰

ssh-keygen -t rsa -C 'yat_ho@163.com'

-t 指定金鑰型別,預設即 rsa ,可以省略
-C 設定註釋文字,比如你的郵箱

預設存放位置

/Users/jenkins/.ssh/id_rsa

將公鑰複製到ssh伺服器

ssh-copy-id jenkins@192.168.1.236

hosts配置

定義主機與組
定義一個IP為192.168.1.21, SSH埠為2135的主機

192.168.1.21:2135

定義一個別名為jumper, SSH埠為22, IP為192.168.1.50的主機

jumper ansible_ssh_port=22 ansible_ssh_host=192.168.1.50

組成員主機名稱範例:

  [test]
  jenkis236 ansible_ssh_port=22 ansible_ssh_host=192.168.1.236

假如你有很多主機遵循某一種模式,你還可以這樣來表示他們:

  [webservers]
  web[1:50].lightcloud.com


  [database]
  db-[a:f].lightcloud.com

定義主機變數

主機可以指定變數, 後面可以供Playbooks呼叫

  [test]
  jenkis236 ansible_ssh_port=22 ansible_ssh_host=192.168.1.236 http_port=8080 

定義組變數

[atlanta]
host1
host2
[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com

Ansible內建連線主機的變數

ansible_ssh_host
  ansible通過ssh連線的IP或者FQDN
ansible_ssh_port
  SSH連線埠
ansible_ssh_user
  預設SSH連線使用者
ansible_ssh_pass
  SSH連線的密碼(這是不安全的,ansible極力推薦使用--ask-pass選項或使用SSH keys)
ansible_sudo_pass
  sudo使用者的密碼
ansible_connection
  SSH連線的型別:local,ssh,paramiko,在ansible 1.2之前預設是paramiko,後來智慧選擇,優先使用基於ControlPersist的ssh(支援的前提)
ansible_ssh_private_key_file
  SSH連線的公鑰檔案
ansible_shell_type
  指定主機所使用的shell直譯器,預設是sh,你可以設定成csh, fish等shell直譯器
ansible_python_interpreter
  用來指定python直譯器的路徑
ansible\_\*\_interpreter
  用來指定主機上其他語法直譯器的路徑,例如ruby,perl等

 Ansible常用模組及API

command: 執行遠端主機SHELL命令

ansible all -i /Users/jenkins/jenkins/lirbary/ansible_hosts/hosts_test -m command -a "ifconfig"

script: 遠端執行MASTER本地SHELL指令碼.(類似scp+shell)

ansible test -i /Users/jenkins/jenkins/lirbary/ansible_hosts/hosts_test -m script -a "../Env_update_shell/test.sh"

copy:實現主控端向目標主機拷貝檔案, 類似scp功能.

ansible test -i /Users/jenkins/jenkins/lirbary/ansible_hosts/hosts -m copy -a "src=~/test.sh dest=/tmp/ owner=root group=root mode=0755"

stat:獲取遠端檔案狀態資訊, 包括atime, ctime, mtime, md5, uid, gid等資訊.

ansible test -i /Users/jenkins/jenkins/lirbary/ansible_hosts/hosts_test -m stat -a "path=/Users/jenkins/jenkins/"

get_url:實現在遠端主機下載指定URL到本地.

ansible test -i /Users/jenkins/jenkins/lirbary/ansible_hosts/hosts_test -m get_url -a "url=http://www.cnblogs.com/yatho dest=/tmp/index.html mode=0400 force=yes"

yum:Linux包管理平臺操作, 常見都會有yum和apt, 此處會呼叫yum管理模式

ansible servers -m yum -a "name=curl state=latest"

cron:遠端主機crontab配置

ansible webservers -m cron -a "name='check dir' hour='5,2' job='ls -alh > /dev/null'"

service:遠端主機系統服務管理

# ansible webservers -m service -a "name=crond state=stopped"
# ansible webservers -m service -a "name=crond state=restarted"
# ansible webservers -m service -a "name=crond state=reloaded"

user:user

新增使用者:
# ansible webservers -m user -a "name=johnd comment='John Doe'"
刪除使用者:
# ansible webservers -m user -a "name=johnd state=absent remove=yes"

 playbook

playbook介紹

playbook是一個不同於使用Ansible命令列執行方式的模式, 其功能是將大量命令列配置整合到一起形成一個可定製的多主機配置管理部署工具.

它通過YAML格式定義, 可以實現向多臺主機的分發應用部署.

 

以下給大家詳細介紹一個針對nginx巢狀複用結構的playbook部署例項:

1. 構建目錄結構

# cd /etc/ansible/

# mkdir group_vars

# mkdir roles

2.定義host

# vi /etc/ansible/hosts

[webservers]
client01.example.com
client02.example.com
[nginx01]
client01.example.com
[nginx02]
client02.example.com

3.定義變數

# vi /etc/ansible/group_vars/nginx01

worker_processes: 4
num_cpus: 4
max_open_file: 65506
root: /data
remote_user: root
# vi /etc/ansible/group_vars/nginx02

worker_processes: 2
num_cpus: 2
max_open_file: 35506
root: /www
remote_user: root

Tips:這裡在group_vars下定義的檔名必須對應hosts檔案下的group標籤, 通過這裡定義的不同引數從而部署不同型別的主機配置.

 

4.建立roles入口檔案

# vi /etc/ansible/site.yml

- hosts: webservers
  roles:
  - base_env
- hosts: nginx01
  roles:
  - nginx01
- hosts: nginx02
  roles:
  - nginx02

  

Tips: 這裡的roles:下的字串需對應roles目錄下的目錄名.

 

5.定義全域性role base_env

建立目錄結構

# mkdir -p /etc/ansible/roles/base_env/tasks 

# vi /etc/ansible/roles/base_env/tasks/main.yml

 

# 將EPEL的yum源配置檔案傳送到客戶端
- name: Create the contains common plays that will run on all nodes 
  copy: src=epel.repo dest=/etc/yum.repos.d/epel.repo
- name: Create the GPG key for EPEL
  copy: src=RPM-GPG-KEY-EPEL-6 dest=/etc/pki/rpm-gpg
  
# 關閉SELINUX
- name: test to see if selling is running
  command: getenforce
  register: sestatus
  changed_when: false

# 刪除iptables預設規則並儲存
- name: remove the default iptables rules
  command: iptables -F
- name: save iptables rules
  command: service iptables save

將對應需要拷貝到遠端的檔案複製到base_env/files目錄下

# mkdir -p  /etc/ansible/roles/base_env/files

# cp /etc/yum.repos.d/epel.repo /etc/ansible/roles/base_env/files

# cp /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 /etc/ansible/roles/base_env/files

6. 定義nginx01和ngnix02 role

建立目錄結構

# mkdir -p /etc/ansible/roles/nginx{01,02}

# mkdir -p /etc/ansible/roles/nginx01/tasks

# mkdir -p /etc/ansible/roles/nginx02/tasks

# vi /etc/ansible/roles/nginx01/tasks/main.yml

 

# 安裝nginx最新版本
- name: ensure nginx is at the latest version
  yum: pkg=nginx state=latest

# 將nginx配置檔案傳送到遠端目錄
- name: write the nginx config file
  template: src=nginx.conf dest=/etc/nginx/nginx.conf
  notify: restart nginx # 重啟nginx

# 建立nginx根目錄
- name: Create Web Root
  file: dest={{ root }} mode=775 state=directory owner=nginx group=nginx
  notify: reload nginx
- name: ensure nginx is running
  service: name=nginx state=restarted
 

 

# cp /home/ansible/roles/nginx01/tasks/main.yml /home/ansible/roles/nginx02/tasks/main.yml

  

7.定義files

# mkdir -p /etc/ansible/roles/nginx01/templates

# mkdir -p /etc/ansible/roles/nginx02/templates

# vi /etc/ansible/roles/nginx01/templates/nginx.conf

# For more information on configuration, see: 

user              nginx;  
worker_processes  {{ worker_processes }};  
{% if num_cpus == 2 %}  
worker_cpu_affinity 01 10;  
{% elif num_cpus == 4 %}  
worker_cpu_affinity 1000 0100 0010 0001;  
{% elif num_cpus >= 8 %}  
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;  
{% else %}  
worker_cpu_affinity 1000 0100 0010 0001;  
{% endif %}  
worker_rlimit_nofile {{ max_open_file }};  
  
error_log  /var/log/nginx/error.log;  
#error_log  /var/log/nginx/error.log  notice;  
#error_log  /var/log/nginx/error.log  info;  
  
pid        /var/run/nginx.pid;  
  
events {  
    worker_connections  {{ max_open_file }};  
}  
  
  
http {  
    include       /etc/nginx/mime.types;  
    default_type  application/octet-stream;  
  
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '  
                      '$status $body_bytes_sent "$http_referer" '  
                      '"$http_user_agent" "$http_x_forwarded_for"';  
  
    access_log  /var/log/nginx/access.log  main;  
  
    sendfile        on;  
    #tcp_nopush     on;  
  
    #keepalive_timeout  0;  
    keepalive_timeout  65;  
  
    #gzip  on;  
      
    # Load config files from the /etc/nginx/conf.d directory  
    # The default server is in conf.d/default.conf  
    #include /etc/nginx/conf.d/*.conf;  
    server {  
        listen       80 default_server;  
        server_name  _;  
  
        #charset koi8-r;  
  
        #access_log  logs/host.access.log  main;  
  
        location / {  
            root   {{ root }};  
            index  index.html index.htm;  
        }  
  
        error_page  404              /404.html;  
        location = /404.html {  
            root   /usr/share/nginx/html;  
        }  
  
        # redirect server error pages to the static page /50x.html  
        #  
        error_page   500 502 503 504  /50x.html;  
        location = /50x.html {  
            root   /usr/share/nginx/html;  
        }  
  
    }  
  
} 

  

Tip: worker_processes, num_cpus, max_open_file, root等引數會呼叫group_vars目錄下配置檔案中相應的變數值

# cp /etc/ansible/roles/nginx01/templates/nginx.conf  /etc/ansible/roles/nginx02/templates/nginx.conf

8.執行playbook

# ansible-playbook -i /etc/ansible/hosts /etc/ansible/site.yml -f 10

Tips: -f 為啟動10個並行程式執行playbook, -i 定義inventory host檔案, site.yml 為入口檔案 

 

PLAY [webservers] ************************************************************* 

GATHERING FACTS *************************************************************** 
ok: [client02.example.com]
ok: [client01.example.com]

TASK: [base_env | Create the contains common plays that will run on all nodes] *** 
ok: [client01.example.com]
ok: [client02.example.com]

TASK: [base_env | Create the GPG key for EPEL] ******************************** 
ok: [client02.example.com]
ok: [client01.example.com]

TASK: [base_env | test to see if selling is running] ************************** 
ok: [client01.example.com]
ok: [client02.example.com]

TASK: [base_env | remove the default iptables rules] ************************** 
changed: [client02.example.com]
changed: [client01.example.com]

TASK: [base_env | save iptables rules] **************************************** 
changed: [client01.example.com]
changed: [client02.example.com]

PLAY [nginx01] **************************************************************** 

GATHERING FACTS *************************************************************** 
ok: [client01.example.com]

TASK: [nginx01 | ensure nginx is at the latest version] *********************** 
ok: [client01.example.com]

TASK: [nginx01 | write the nginx config file] ********************************* 
ok: [client01.example.com]

TASK: [nginx01 | Create Web Root] ********************************************* 
ok: [client01.example.com]

TASK: [nginx01 | ensure nginx is running] ************************************* 
changed: [client01.example.com]

PLAY [nginx02] **************************************************************** 

GATHERING FACTS *************************************************************** 
ok: [client02.example.com]

TASK: [nginx02 | ensure nginx is at the latest version] *********************** 
ok: [client02.example.com]

TASK: [nginx02 | write the nginx config file] ********************************* 
ok: [client02.example.com]

TASK: [nginx02 | Create Web Root] ********************************************* 
ok: [client02.example.com]

TASK: [nginx02 | ensure nginx is running] ************************************* 
changed: [client02.example.com]

PLAY RECAP ******************************************************************** 
client01.example.com       : ok=11   changed=3    unreachable=0    failed=0   
client02.example.com       : ok=11   changed=3    unreachable=0    failed=0 

最終部署目錄結構如下

# tree /etc/ansible/

/etc/ansible/
├── ansible.cfg
├── group_vars
│   ├── nginx01
│   └── nginx02
├── hosts
├── hosts.bak
├── roles
│   ├── base_env
│   │   ├── files
│   │   │   ├── epel.repo
│   │   │   └── RPM-GPG-KEY-EPEL-6
│   │   └── tasks
│   │       └── main.yml
│   ├── nginx01
│   │   ├── tasks
│   │   │   └── main.yml
│   │   └── templates
│   │       └── nginx.conf
│   └── nginx02
│       ├── tasks
│       │   └── main.yml
│       └── templates
│           └── nginx.conf
└── site.yml

 jenkins關聯配置

Choice Parameter
  deploy_environment  定義部署環境名 dev,test,uat,pdt
Execute shell
  開頭和結尾的set +x, set -x用來開啟和關閉該部分的擴充套件引數及命令
  cd $WORKSPACE/leon-playbook-phpcms1.1
  ansible --version
  ansible-playbook -i inventory/$deploy_environment ./deploy.yml -e project=phpcms -e branch=$branch_selector -e env=$deploy_environment
  -i 用來自定義ansible host檔案路徑, ./deploy.yml為ansible-playbook入口檔案, -e 後可跟給當前session新增的環境變數.

相關文章