接Jenkins+Gitlab+Ansbile自動化部署(一):http://www.javashuo.com/article/p-tzgbojrp-kw.htmlhtml
Ansible的配置與部署python
工具名稱 | 介紹 |
Chef | 採用Ruby編寫,C/S架構,配置須要Git依賴,Recipe腳本編寫規範,須要良好的編程經驗。 |
Ansible | 採用Python編寫,無Client,模塊化配置管理,Playbook腳本編寫規範,易於上手,nginx 適合中小規模快速部署。git |
Saltstack | 採用Python編寫,C/S架構,模塊化配置管理,YAML腳本編寫規範,內置github 異步文件服務器能夠爲客戶端文件加快服務速度,適合大規模集羣部署,可是須要安裝客戶端。shell |
Ansible的優點和應用場景編程
優點:vim
Ansible配合virtualenv安裝配置centos
使用python自帶的python virtualenv工具隔離Python3.六、Ansible2.5和系統其餘python依賴環境。服務器
Ansible安裝方式
1.yum一鍵安裝(不推薦)
[root@ansible ~]# yum install -y ansible # 雖然簡單,可是會帶來一系列的依賴和模塊混亂
2.Git源碼安裝(推薦)
[root@ansible ~]# yum install -y git #若是系統中沒有git的話,使用這條命令安裝便可 [root@ansible ~]# git clone https://github.com/ansible/ansible.git
Ansible2.5+Python3.6安裝步驟
1.安裝python3.6.5和virtualenv工具
[root@ansible ~]# wget http://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.xz [root@ansible ~]# tar -xf Python-3.6.5.tar.xz -C /usr/local/src/ [root@ansible ~]# cd /usr/local/src/Python-3.6.5/ [root@ansible ~]# cd /usr/local/src/Python-3.6.5/ [root@ansible Python-3.6.5]# ./configure --prefix=/usr/local/ --with-ensurepip=install --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib" #居然報錯 configure: error: in `/usr/local/src/Python-3.6.5': configure: error: no acceptable C compiler found in $PATH See `config.log' for more details # 根據報錯信息,須要安裝GCC套件 [root@ansible Python-3.6.5]# yum install -y gcc # 而後再次執行編譯操做,完事執行安裝 [root@ansible Python-3.6.5]# make && make altinstall # 然而又報錯了 .... import pip zipimport.ZipImportError: can't decompress data; zlib not available make: *** [altinstall] Error 1 # 提示很明顯了直接執行 [root@ansible Python-3.6.5]# yum install zlib* # 而後再吃運行安裝命令便可 [root@ansible Python-3.6.5]# make && make altinstall # 當看到 ..... Collecting setuptools Collecting pip Installing collected packages: setuptools, pip Successfully installed pip-9.0.3 setuptools-39.0.1 # 代表安裝成功 # 接着安裝virtualenv,然而並不順利 [root@ansible bin]# pwd /usr/local/bin [root@ansible bin]# ./pip --trusted-host pypi.python.org install virtualenv pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. Collecting virtualenv Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/ Could not fetch URL https://pypi.python.org/simple/virtualenv/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/virtualenv/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping Could not find a version that satisfies the requirement virtualenv (from versions: ) No matching distribution found for virtualenv # 使用網友提供的方法 加上--trusted-host參數,哦...依然不行 [root@ansible bin]# ./pip --trusted-host pypi.python.org install virtualenv pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. Collecting virtualenv Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/ Could not fetch URL https://pypi.python.org/simple/virtualenv/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/virtualenv/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping Could not find a version that satisfies the requirement virtualenv (from versions: ) No matching distribution found for virtualenv # 根據第一行報錯提示 pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available # 須要安裝openssl相關軟件包 [root@ansible bin]# yum install -y openssl* #除此以外,卸載掉python2.7安裝的pip防止干擾 [root@ansible bin]# python -m pip uninstall pip Uninstalling pip-18.1: Would remove: /usr/bin/pip /usr/bin/pip2 /usr/bin/pip2.7 /usr/lib/python2.7/site-packages/pip-18.1.dist-info/* /usr/lib/python2.7/site-packages/pip/* Proceed (y/n)? y Successfully uninstalled pip-18.1 # 而後回到解壓包裏,從新運行編譯安裝過程 [root@ansible Python-3.6.5]# ./configure --prefix=/usr/local/ --with-ensurepip=install --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib" [root@ansible Python-3.6.5]# make && make altinstall ....... Requirement already satisfied: setuptools in /usr/local/lib/python3.6/site-packages Requirement already satisfied: pip in /usr/local/lib/python3.6/site-packages [root@ansible Python-3.6.5]# cd ../../bin/ [root@ansible bin]# ll total 68 -rwxr-xr-x. 1 root root 101 Jan 7 11:42 2to3-3.6 -rwxr-xr-x. 1 root root 242 Jan 7 11:00 easy_install-3.6 -rwxr-xr-x. 1 root root 99 Jan 7 11:42 idle3.6 lrwxrwxrwx. 1 root root 21 Jan 7 11:03 pip -> /usr/local/bin/pip3.6 -rwxr-xr-x. 1 root root 214 Jan 7 11:00 pip3.6 -rwxr-xr-x. 1 root root 84 Jan 7 11:42 pydoc3.6 -rwxr-xr-x. 2 root root 17712 Jan 7 11:41 python3.6 -rwxr-xr-x. 2 root root 17712 Jan 7 11:41 python3.6m -rwxr-xr-x. 1 root root 3109 Jan 7 11:42 python3.6m-config -rwxr-xr-x. 1 root root 441 Jan 7 11:42 pyvenv-3.6 [root@ansible bin]# ln -s /usr/local/bin/pip3.6 /usr/local/bin/pip # 再次使用pip安裝virtualenv [root@ansible bin]# pip install virtualenv Collecting virtualenv Cache entry deserialization failed, entry ignored Cache entry deserialization failed, entry ignored Downloading https://files.pythonhosted.org/packages/6a/d1/e0d142ce7b8a5c76adbfad01d853bca84c7c0240e35577498e20bc2ade7d/virtualenv-16.2.0-py2.py3-none-any.whl (1.9MB) 100% |████████████████████████████████| 1.9MB 64kB/s Requirement already satisfied: setuptools>=18.0.0 in /usr/local/lib/python3.6/site-packages (from virtualenv) Installing collected packages: virtualenv Successfully installed virtualenv-16.2.0 You are using pip version 9.0.3, however version 18.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. # 安裝成功
2.建立ansible帳戶並安裝python3.6.5版本virtualenv實例
[root@ansible ~]# useradd deploy && su - deploy [deploy@ansible ~]$ virtualenv -p /usr/local/bin/python3.6 .py3-a2.5-env Already using interpreter /usr/local/bin/python3.6 Using base prefix '/usr/local' New python executable in /home/deploy/.py3-a2.5-env/bin/python3.6 Also creating executable in /home/deploy/.py3-a2.5-env/bin/python Installing setuptools, pip, wheel... done. [deploy@ansible ~]$
3.Git源碼安裝ansible2.5
# 首先使用root帳戶確保git nss curl命令已經安裝 [root@ansible ~]# yum install -y git nss curl # 而後切到deploy用戶,進入以前建立的.py3-a2.5-env目錄下 [deploy@ansible ~]$ cd /home/deploy/.py3-a2.5-env/ [deploy@ansible .py3-a2.5-env]$ git clone https://github.com/ansible/ansible.git
4. 加載python3.6.5 virtualenv環境
[deploy@ansible .py3-a2.5-env]$ source /home/deploy/.py3-a2.5-env/bin/activate (.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$
5. 安裝ansible依賴包
# 安裝依賴包 (.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ pip install paramiko PyYAML jinja2 (.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ ll total 8 drwxrwxr-x. 14 deploy deploy 4096 Jan 7 13:31 ansible drwxrwxr-x. 2 deploy deploy 4096 Jan 7 11:52 bin drwxrwxr-x. 2 deploy deploy 24 Jan 7 11:52 include drwxrwxr-x. 3 deploy deploy 23 Jan 7 11:52 lib (.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ pwd /home/deploy/.py3-a2.5-env
6. 在python3.6.5虛擬環境下加載ansible2.5
# 確認ansible源碼包在.py3-a2.5-env目錄下 # 進入ansible目錄 (.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ cd ansible/ (.py3-a2.5-env) [deploy@ansible ansible]$ pwd /home/deploy/.py3-a2.5-env/ansible (.py3-a2.5-env) [deploy@ansible ansible]$ git checkout stable-2.5 #將ansible切換到2.5版本 Branch stable-2.5 set up to track remote branch stable-2.5 from origin. Switched to a new branch 'stable-2.5' (.py3-a2.5-env) [deploy@ansible ansible]$ source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q #在此虛擬環境下加載ansible2.5版本
7.驗證ansible版本
(.py3-a2.5-env) [deploy@ansible ansible]$ ansible --version ansible 2.5.14 (stable-2.5 6548b7a558) last updated 2019/01/07 13:56:01 (GMT +800) config file = None configured module search path = ['/home/deploy/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/deploy/.py3-a2.5-env/ansible/lib/ansible executable location = /home/deploy/.py3-a2.5-env/ansible/bin/ansible python version = 3.6.5 (default, Jan 7 2019, 11:40:52) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] # 至此ansible2.5在虛擬環境下安裝加載完成
Playbooks框架與格式
父目錄 | 1級子目錄 | 2級子目錄 | |
inventory/ | Server詳細清單目錄 | 用來保存主機域名、IP地址和相關參數 | |
testenv | 具體清單與變量聲明文件 | ||
roles/ | roles任務列表 | 能夠存放一個或多個role | |
testbox/ | testbox詳細任務 | ||
tasks/ | |||
main.yml | testbox主任務文件 | ||
deploy.yml | Playbook任務入口文件 |
格式說明
testenv文件 | 說明 |
[testservers] | Server組列表 |
test.example.com | 目標部署服務器主機名 |
[testservers:vars] | Server組列表參數 |
server_name=test,example.com | 目標主機Key/Value參數 |
user=root | |
output=/root/test.txt |
主任務文件main.yml
文件內容 | 說明 |
- name:Print Server name and user to remote testbox | 任務名稱 |
shell:"echo 'Currently{{user}} is logining {{server_name}}' > {{output}}" | shell:使用shell模塊執行命令 |
inventory/testenv文件[testservers:vars] server_name=test.example.com user=root output=/root/test.txt |
任務入口文件deploy.yml
- hosts:"testservers" #Server列表 gather_facts:true #獲取Server基本信息 remote_user:root # 目標服務器系統用戶指定 roles: - testbox #進入roles/testbox任務目錄
登陸ansible主機,加載以前配置好的python3.6.5和ansible2.5環境,並驗證
[root@ansible ~]# su - deploy Last login: Mon Jan 7 11:51:41 CST 2019 on pts/1 [deploy@ansible ~]$ source .py3-a2.5-env/bin/activate (.py3-a2.5-env) [deploy@ansible ~]$ source .py3-a2.5-env/ansible/hacking/env-setup -q (.py3-a2.5-env) [deploy@ansible ~]$ ansible-playbook --version ansible-playbook 2.5.14 (stable-2.5 6548b7a558) last updated 2019/01/07 13:56:01 (GMT +800) config file = None configured module search path = ['/home/deploy/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/deploy/.py3-a2.5-env/ansible/lib/ansible executable location = /home/deploy/.py3-a2.5-env/ansible/bin/ansible-playbook python version = 3.6.5 (default, Jan 7 2019, 11:40:52) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
開始編寫playbooks
(.py3-a2.5-env) [deploy@ansible ~]$ mkdir test-playbooks (.py3-a2.5-env) [deploy@ansible ~]$ cd test-playbooks/ (.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir inventory (.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir roles (.py3-a2.5-env) [deploy@ansible test-playbooks]$ cd inventory (.py3-a2.5-env) [deploy@ansible inventory]$ vim testenv [testservers] test.example.com [testservers:vars] server_name=test.example.com user=root output=/root/test.txt (.py3-a2.5-env) [deploy@ansible inventory]$ cd .. (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ls inventory roles (.py3-a2.5-env) [deploy@ansible test-playbooks]$ cd roles/ (.py3-a2.5-env) [deploy@ansible roles]$ mkdir testbox (.py3-a2.5-env) [deploy@ansible roles]$ cd testbox/ (.py3-a2.5-env) [deploy@ansible testbox]$ mkdir tasks (.py3-a2.5-env) [deploy@ansible testbox]$ cd tasks/ (.py3-a2.5-env) [deploy@ansible tasks]$ vim main.yml - name: Print server name and user to remote testbox shell:"echo 'Currently {{ user }} is loggging {{ server_name }}' > {{ output }}" (.py3-a2.5-env) [deploy@ansible tasks]$ cd ../../.. (.py3-a2.5-env) [deploy@ansible test-playbooks]$ pwd /home/deploy/test-playbooks (.py3-a2.5-env) [deploy@ansible tasks]$ cd ../../.. (.py3-a2.5-env) [deploy@ansible test-playbooks]$ pwd /home/deploy/test-playbooks (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim deploy.yml - hosts: "testservers" gather_facts: true remote_user: root
roles:
- testbox
查看test_playbooxs目錄結構
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ tree . . ├── deploy.yml ├── inventory │?? └── testenv └── roles └── testbox └── tasks └── main.yml 4 directories, 3 files
這裏須要另一臺測試被部署機器test.example.com
系統版本 | 主機名 | IP地址 |
CentOS Linux release 7.5.1804 (core) | test.example.com | 192.168.244.133 |
被部署的機器test.example.com與其餘三臺主機實驗環境一致。
配置SSH免祕鑰認證
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ su - root Password: Last login: Mon Jan 7 10:05:23 CST 2019 from 192.168.244.1 on pts/1 [root@ansible ~]# vim /etc/hosts .... 192.168.244.133 test.example.com [root@ansible ~]# exit logout (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/deploy/.ssh/id_rsa): Created directory '/home/deploy/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/deploy/.ssh/id_rsa. Your public key has been saved in /home/deploy/.ssh/id_rsa.pub. The key fingerprint is: SHA256:Aj+FzKSwqZS19eI/3EQt13L78+u3vjMtseX8YXNFnnY deploy@ansible.example.com The key's randomart image is: +---[RSA 2048]----+ | .. .. | | o+o=.. . . | | oo.o.+..o + o .| |.. .o... o o .o.| |. .+ S. . oE| | ooo + +| | + . %o| | . +o@| | oB@| +----[SHA256]-----+ (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh-copy-id -i /home/deploy/.ssh/id_rsa.pub root@test.example.com /bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/deploy/.ssh/id_rsa.pub" The authenticity of host 'test.example.com (192.168.244.133)' can't be established. ECDSA key fingerprint is SHA256:66hu+WU6R2SL4+7r/WYk2kjrGi7IwjuJieTrdMhwLc0. ECDSA key fingerprint is MD5:af:c7:bd:88:0d:40:d8:19:6d:28:7f:dd:af:aa:3a:c9. Are you sure you want to continue connecting (yes/no)? yes /bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys root@test.example.com's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'root@test.example.com'" and check to make sure that only the key(s) you wanted were added. (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com Last login: Mon Jan 7 17:35:38 2019 from 192.168.244.1 [root@test ~]# whoami root [root@test ~]# hostname test.example.com
測試部署
(.py3-a2.5-env) [deploy@ansible ~]$ cd test-playbooks/ (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ls deploy.yml inventory roles (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml PLAY [testservers] ************************************************************* TASK [Gathering Facts] ********************************************************* ok: [test.example.com] TASK [testbox : Print server name and user to remote testbox] ****************** changed: [test.example.com] PLAY RECAP ********************************************************************* test.example.com : ok=2 changed=1 unreachable=0 failed=0 # 如下內容能夠看出已經成功在遠程被部署主機test.example.com上建立一個test.txt文件,且文件內容與預先設置的一致 (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com Last login: Mon Jan 7 17:42:57 2019 from 192.168.244.132 [root@test ~]# ls anaconda-ks.cfg test.txt [root@test ~]# cat test.txt Currently root is loggging test.example.com
Ansible Playbooks經常使用模塊
File模塊:
在目標主機建立文件或目錄,並賦予其系統權限,如:
- name: create a file # 任務名稱 file: 'path=/root/a.txt state=touch mode=0755 owner=sishen group=sishen' # 任務內容
Copy模塊:
實現Ansible服務端到目標主機的文件傳送,如:
- name: copy a file #任務名稱 複製一個文件 copy: 'remote_src=no src=roles/testbox/files/test.sh dest=/root/test.sh mode=0644 force=yes' # 說明 remote_src:聲明將ansible服務端文件傳送到目標主機當中 src:源文件的路徑 dest:目標文件的路徑 mode:賦予的文件權限 force:強制執行
Stat模塊:
獲取遠程文件狀態信息,如:
- name: check if test.sh exists stat: 'path=/root/test.sh' #須要獲取的文件路徑 register: script_stat #將stat變量獲取到的信息傳遞給script_stat
Debug模塊:
打印語句到Ansible執行輸出:
- debug: msf=test.sh exists when:script_stat.stat.exists
Command/Shell模塊
用來執行Linux目標主機命令行
- name: run the script command: "sh /root/test.sh" - name: run the script shell: "echo 'test' > /root/test.txt" (推薦)
Template模塊
實現Ansible服務端到目標主機的jinja2模板傳送
- name: write the nginx config file template: src=roles/testbox/templates/nginx.conf.j2 dest=/etc/nginx/nginx.conf
Packaging模塊
調用目標主機系統包管理工具(yum,apt)進行安裝
- name: ensure nginx is at the latest version yum: pkg=nginx state=latest #(CentOS/RHEL) - name: ensure nginx is at the latest version apt: pkg=nginx state=latest #(Debian/Ubuntu)
Service模塊
管理目標主機系統服務
- name: start nginx service
service: name=nginx state=started
登陸被部署主機,建立測試用戶
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com Last login: Mon Jan 7 17:44:56 2019 from 192.168.244.132 [root@test ~]# useradd sishen useradd: user 'sishen' already exists [root@test ~]# useradd god [root@test ~]# useradd deploy [root@test ~]# mkdir /etc/nginx [root@test ~]# rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm Retrieving http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm warning: /var/tmp/rpm-tmp.i5SPeu: Header V4 RSA/SHA1 Signature, key ID 7bd9bf62: NOKEY Preparing... (100%################################# [100%] Updating / installing... 1:nginx-release-centos-7-0.el7.ngx ( 81%################################# [100%]
退出被部署主機
[root@test ~]# exit logout Connection to test.example.com closed. (.py3-a2.5-env) [deploy@ansible test-playbooks]$ pwd /home/deploy/test-playbooks (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ls deploy.yml inventory roles (.py3-a2.5-env) [deploy@ansible test-playbooks]$ (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml - name: Print server name and user to remote testbox shell: "echo 'Currently {{ user }} is loggging {{ server_name }}' > {{ output }}" #添加如下內容 - name: create a file file: 'path=/root/god.txt state=touch mode=0755 owner=god group=god' (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml PLAY [testservers] ************************************************************* TASK [Gathering Facts] ********************************************************* ok: [test.example.com] TASK [testbox : Print server name and user to remote testbox] ****************** changed: [test.example.com] TASK [testbox : create a file] ************************************************* changed: [test.example.com] PLAY RECAP ********************************************************************* test.example.com : ok=3 changed=2 unreachable=0 failed=0
登陸到遠程主機查看
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com Last login: Mon Jan 7 19:05:41 2019 from 192.168.244.132 [root@test ~]# ls -l total 8 -rw-------. 1 root root 1732 Dec 26 20:03 anaconda-ks.cfg -rwxr-xr-x. 1 god god 0 Jan 7 19:05 god.txt #已經成功建立並賦予文件權限 -rw-r--r--. 1 root root 44 Jan 7 19:05 test.txt
或者直接
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com ls -l /root/god.txt -rwxr-xr-x. 1 god god 0 Jan 7 19:05 /root/god.txt
建立god.sh
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir roles/testbox/files (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/files/god.sh echo "this is a test script" echo "If you see this message, the script is executed successfully." (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml - name: Print server name and user to remote testbox shell: "echo 'Currently {{ user }} is loggging {{ server_name }}' > {{ output }}" - name: create a file file: 'path=/root/god.txt state=touch mode=0755 owner=god group=god' #添加如下內容 - name: copy a file copy: 'remote_src=no src=roles/testbox/files/god.sh dest=/root/god.sh mode=0644 force=yes' (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml
驗證並查看
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com ls -l /root/god.sh -rw-r--r--. 1 root root 99 Jan 7 19:19 /root/god.sh
演示stat與debug模塊
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml .... # 文件末尾添加如下內容 - name: check if god.sh exists stat: 'path=/root/gid.sh' register: script_stat - debug: msg="god.sh exists" when: script_stat.stat.exists (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml PLAY [testservers] ************************************************************* TASK [Gathering Facts] ********************************************************* ok: [test.example.com] TASK [testbox : Print server name and user to remote testbox] ****************** changed: [test.example.com] TASK [testbox : create a file] ************************************************* changed: [test.example.com] TASK [testbox : copy a file] *************************************************** ok: [test.example.com] TASK [testbox : check if god.sh exists] **************************************** ok: [test.example.com] TASK [testbox : debug] ********************************************************* ok: [test.example.com] => { "msg": "god.sh exists" } PLAY RECAP ********************************************************************* test.example.com : ok=6 changed=2 unreachable=0 failed=0 (.py3-a2.5-env) [deploy@ansible test-playbooks]$
演示command模塊
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml # 末尾添加如下內容 - name: run the script command: 'sh /root/god.sh' (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml PLAY [testservers] ************************************************************* TASK [Gathering Facts] ********************************************************* ok: [test.example.com] TASK [testbox : Print server name and user to remote testbox] ****************** changed: [test.example.com] TASK [testbox : create a file] ************************************************* changed: [test.example.com] TASK [testbox : copy a file] *************************************************** ok: [test.example.com] TASK [testbox : check if god.sh exists] **************************************** ok: [test.example.com] TASK [testbox : debug] ********************************************************* ok: [test.example.com] => { "msg": "god.sh exists" } TASK [testbox : run the script] ************************************************ changed: [test.example.com] PLAY RECAP ********************************************************************* test.example.com : ok=7 changed=3 unreachable=0 failed=0
template模塊演示
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim inventory/testenv # 末尾添加如下內容 server_name=test.example.com port=80 user=deploy worker_processes=4 max_open_file=65505 root=/www
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir roles/testbox/templates (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/templates/nginx.conf.j2 # For more information on configuration, see: user {{ user }}; worker_processes {{ worker_processes }}; error_log /var/log/nginx/error.log; 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 {{ port }} default_server; server_name {{ 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; } } } 配置main.yml文件 (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml # 末尾添加以下內容 - name: write the nginx config file template: src=roles/testbox/templates/nginx.conf.j2 dest=/etc/nginx/nginx.c onf - name: ensure nginx is at the latest version yum: pkg=nginx state=latest - name: start nginx service service: name=nginx state=started (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml PLAY [testservers] ************************************************************* TASK [Gathering Facts] ********************************************************* ok: [test.example.com] TASK [testbox : Print server name and user to remote testbox] ****************** changed: [test.example.com] TASK [testbox : create a file] ************************************************* changed: [test.example.com] TASK [testbox : copy a file] *************************************************** ok: [test.example.com] TASK [testbox : check if god.sh exists] **************************************** ok: [test.example.com] TASK [testbox : debug] ********************************************************* ok: [test.example.com] => { "msg": "god.sh exists" } TASK [testbox : run the script] ************************************************ changed: [test.example.com] TASK [testbox : write the nginx config file] *********************************** changed: [test.example.com] TASK [testbox : ensure nginx is at the latest version] ************************* changed: [test.example.com] TASK [testbox : start nginx service] ******************************************* changed: [test.example.com] PLAY RECAP ********************************************************************* test.example.com : ok=10 changed=6 unreachable=0 failed=0 (.py3-a2.5-env) [deploy@ansible test-playbooks]$
查看並驗證
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com cat /etc/nginx/nginx.conf # For more information on configuration, see: user deploy; worker_processes 4; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events { worker_connections 65505; } 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 test.example.com; #charset koi8-r; #access_log logs/host.access.log main; location / { root /www; 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; } } } (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com ps -ef | grep nginx root 5047 1 0 19:49 ? 00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf deploy 5048 5047 0 19:49 ? 00:00:00 nginx: worker process deploy 5049 5047 0 19:49 ? 00:00:00 nginx: worker process deploy 5050 5047 0 19:49 ? 00:00:00 nginx: worker process deploy 5051 5047 0 19:49 ? 00:00:00 nginx: worker process
至此ansible的安裝、配置與演示已所有完成。