iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 25
1
Kubernetes

在地端建置Angular+ASP.NET Core的DevOps環境系列 第 25

day25_ansible03_module01_apt,become,with_items,service,handlers,notify,Files,inlinfile

  • 分享至 

  • xImage
  •  

搜哩,標題限100字,列不完
好家在刪了apache2_module後就低於100字了
會全列是希望方便大大們以後查找

前言

剩5天就要完賽了,快完賽了,有種莫名的失落感na~
這次的鐵人賽中,除了感覺k8s博大精深之外
另外就是覺得ansible真的是好用工具,不管你是哪個領域,都可以學起來
尤其是1個人全包的那種(伺服器、網管、資訊系統開發&維運、資安...總之就是全包)
所以,
今天開始~完賽的5天(day25~day30)就來把ansible基礎學得更完整吧~
其實是k8s掰不出文章了

apt

官網文件:
https://docs.ansible.com/ansible/latest/modules/apt_module.html

  • webserver.yaml
---
- hosts : webserver
  become  : true # 類似sudo,升權限
  tasks :
    - name  : install apache2
      apt :  name=apache2  state=present update_cache=yes
# become
# https://docs.ansible.com/ansible/latest/user_guide/become.html

$ ansible-playbook webserver.yaml

https://docs.ansible.com/ansible/latest/modules/apt_module.html

state = absent|build-dep|latest|present

  • latest:確認安裝的是最新版的,present不知道是什麼意思
  • update_cache=yes 等於在apt-get install前,先apt-get update

再來看一下範例

- name: Install apache httpd but avoid starting it immediately (state=present is optional)
  apt:
    name: apache2
    state: present
  environment:
    RUNLEVEL: 1

===

with_items

類似for...each loop的效果

範例1

  • 使用前
---
- hosts : webserver
  become  : true
  tasks :
    - name  : install apache2
      apt :  name=apache2  state=present update_cache=yes
    - name  : install libapache2-mod-swgi
      apt :  name=libapache2-mod-swgi  state=present update_cache=yes
    - name  : install python-pip
      apt :  name=python-pip  state=present update_cache=yes
    - name  : install python-virtualenv
      apt :  name=python-virtualenv  state=present update_cache=yes
  • 使用後
---
- hosts : webserver
  become  : true
  tasks :
    - name  : install web components
      apt :  name={{ item }}}  state=present update_cache=yes
      with_items  :  # item會一個個帶進去,等於apt跑4次
        - apache2
        - libapache2-mod-wsgi
        - python-pip
        - python-virtualenv

範例2

- name: get active sites
  shell: ls -1 /etc/nginx/sites-enabled # 想像成輸出是多行的lines
  register: active # 把shell的執行結果存到active
  changed_when: "active.stdout_lines != sites.keys()" # 當有改變的時候,更新變數active

- name: de-activate sites
  file: path=/etc/nginx/sites-enabled/{{ item }} state=absent # 3 把這個檔案刪掉 # 
  with_items: active.stdout_lines # 1 每行讀出來 item
  when: item not in sites # 2 # 假設sites是dict(key-value),轉成items後,這裡比的是item.key

===

service

https://docs.ansible.com/ansible/latest/modules/service_module.html

enable(跟state有點關係,enable跟state至少要存在1個)

-yes # service enable
-no

state

  • reloaded
  • restarted
  • started # 當然service也會跑起來,有這個就不用enable啦
  • stopped
# 如果已經started,應該就不會作動了吧
- name: Start service httpd, if not started
  service:
    name: httpd
    state: started

- name: Restart service httpd, in all cases
  service:
    name: httpd
    state: restarted
# 不知道差異…
- name: Enable service httpd, and not touch the state
  service:
    name: httpd
    enabled: yes
# 某個執行檔跑service的
- name: Start service foo, based on running process /usr/bin/foo
  service:
    name: foo
    pattern: /usr/bin/foo
    state: started
# 指定網卡restart
- name: Restart network service for interface eth0
  service:
    name: network
    state: restarted
    args: eth0

===

handler 類似先寫好的function

notify 去call handler

https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html#handlers-running-operations-on-change

基本型

- name: template configuration file
  template:
    src: template.j2
    dest: /etc/foo.conf
  notify:
     - restart memcached # 去call 「restart memcached」的handler
     - restart apache
# 通常都寫在下面
handlers:
    - name: restart memcached
      service:
        name: memcached
        state: restarted
    - name: restart apache
      service:
        name: apache
        state: restarted

透過listen去觸發handlers

(如果要一次觸發多個handlers,就很好用)

handlers:
    - name: restart memcached
      service:
        name: memcached
        state: restarted
      listen: "restart web services"
    - name: restart apache
      service:
        name: apache
        state:restarted
      listen: "restart web services"

tasks:
    - name: restart everything
      command: echo "this task will restart the web services"
      notify: "restart web services" # 去call handler

apache2_module

https://docs.ansible.com/ansible/latest/modules/apache2_module_module.html

# enables the Apache2 module "wsgi"
- apache2_module:
    state: present # enable
    name: wsgi # apache2 module的名稱
# disables the Apache2 module "wsgi"
- apache2_module:
    state: absent # disable
    name: wsgi
# disable default modules for Debian
- apache2_module:
    state: absent
    name: autoindex
    force: True # 強制
# disable mpm_worker and ignore warnings about missing mpm module
- apache2_module:
    state: absent
    name: mpm_worker
    ignore_configcheck: True # 乎略警告
# enable dump_io module, which is identified as dumpio_module inside apache2
- apache2_module:
    state: present
    name: dump_io
    identifier: dumpio_module # 啟用,在apache2設定檔中,標識為dumpio_module的module

===

Files:copy

https://docs.ansible.com/ansible/latest/modules/copy_module.html

- name: example copying file with owner and permissions
  copy:
    src: /srv/myfiles/foo.conf # 把這個檔案
    dest: /etc/foo.conf # copy到這裡
    owner: foo # 設權限(owner)
    group: foo # 設權限(群組)
    mode: 0644 # 設權限


- name: The same example as above, but using a symbolic mode equivalent to 0644
  copy:
    src: /srv/myfiles/foo.conf
    dest: /etc/foo.conf
    owner: foo
    group: foo
    mode: u=rw,g=r,o=r(user:read/write、group:read、other:read)

- name: Another symbolic mode example, adding some permissions and removing others
  copy:
    src: /srv/myfiles/foo.conf
    dest: /etc/foo.conf
    owner: foo
    group: foo
    mode: u+rw,g-wx,o-rwx

- name: Copy a new "ntp.conf file into place, backing up the original if it differs from the copied version
  copy:
    src: /mine/ntp.conf
    dest: /etc/ntp.conf
    owner: root
    group: root
    mode: 0644
    backup: yes 
# 如果與原檔案不同,保留原檔案
# 保留的檔案,後面會加時間
# /path/to/file.txt.2015-02-12@22:09~

- name: Copy a new "sudoers" file into place, after passing validation with visudo
  copy:
    src: /mine/sudoers
    dest: /etc/sudoers
    validate: /usr/sbin/visudo -cf %s # file path透過%s來傳給validate
# validate是非常重要的參數,會幫你驗證sudo規則是否可被系統接授
# visudo # http://linux.vbird.org/linux_basic/0410accountmanager.php
# 若想要使用 sudo 執行屬於 root 的權限指令,則 root 需要先使用 visudo 去修改 /etc/sudoers 

- name: Copy a "sudoers" file on the remote machine for editing
  copy:
    src: /etc/sudoers
    dest: /etc/sudoers.edit
    remote_src: yes
    validate: /usr/sbin/visudo -cf %s

- name: Copy using the 'content' for inline data
  copy:
    content: '# This file was moved to /etc/other.conf' # 只寫一行
    dest: /etc/mine.conf'

#Files:file

# change file ownership, group and mode
- file:
    path: /etc/foo.conf
    owner: foo
    group: foo
    # when specifying mode using octal numbers, add a leading 0
    mode: 0644
- file:
    path: /work
    owner: root
    group: root
    mode: 01777
- file:
    src: /file/to/link/to
    dest: /path/to/symlink
    owner: foo
    group: foo
    state: link 
      # state:link the symbolic link will be created or changed
      # sybolick link 會新增或變更

- file:
    src: '/tmp/{{ item.src }}'
    dest: '{{ item.dest }}'
    state: link
  with_items:
    - { src: 'x', dest: 'y' }
    - { src: 'z', dest: 'k' }

# touch a file, using symbolic modes to set the permissions (equivalent to 0644)
- file:
    path: /etc/foo.conf
    state: touch
    mode: "u=rw,g=r,o=r"

# touch the same file, but add/remove some permissions
- file:
    path: /etc/foo.conf
    state: touch
    mode: "u+rw,g-wx,o-rwx"

# touch again the same file, but dont change times
# this makes the task idempotents
- file:
    path: /etc/foo.conf
    state: touch
    mode: "u+rw,g-wx,o-rwx"
    modification_time: "preserve"
    access_time: "preserve"

# create a directory if it doesn't exist
- file:
    path: /etc/some_directory
    state: directory # 建目錄
    mode: 0755

# updates modification and access time of given file
- file:
    path: /etc/some_file
    state: file
    mode: 0755
    modification_time: now
    access_time: now
# state:absent
    - name: delete
      file: path=/etc/xxx.conf
	  state=absent
      # state:absent
      # directories will be recursively deleted, and files or symlinks will be unlinked.
      # 目錄、子目錄都會刪掉,ln -s的symlinks也會刪掉,蠻好用的

===

File:template

https://docs.ansible.com/ansible/latest/modules/template_module.html
http://jinja.pocoo.org/docs/2.10/templates/
假設在nginx這個role有個template

  • roles/nginx/templates/nginx.conf.j2
upstream {{ item.key }} {
{% for server in groups.webserver %}
    server {{ server }}:{{ item.value.backend }};
{% endfor %}
}

server {
    listen {{ item.value.frontend }};

    location / {
        proxy_pass http://{{ item.key }};
    }
}

roles/nginx/tasks/main.yaml

- name: configure nginx sites
# 把template copy到dest
  -template: 
		src=nginx.conf.j2 
		dest=/etc/nginx/sites-available/{{ item.key }} 
		mode=0644 
  with_dict: sites
  notify: restart nginx

# Copy a new "sudoers" file into place, after passing validation with visudo
- template:
    src: /mine/sudoers
    dest: /etc/sudoers
    validate: '/usr/sbin/visudo -cf %s'
    backup: yes
    

===

inlinefile

https://docs.ansible.com/ansible/latest/modules/lineinfile_module.html#examples
改變文件中的1行
如果要改多行,請用replace module_defaults
如果要變更一個block,請用blockinfile

列一些比較簡單的範例

# Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- lineinfile: # 對file裡的line進行操作 = ="
    path: /etc/selinux/config
    regexp: '^SELINUX=' # 可以用正則表達式來找字串
    line: 'SELINUX=enforcing' # 替代文字
- lineinfile:
    path: /etc/httpd/conf/httpd.conf
    regexp: '^Listen '
    insertafter: '^#Listen ' # 加在後面
    line: 'Listen 8080'
# Validate the sudoers file before saving
- lineinfile:
    path: /etc/sudoers
    state: present
    regexp: '^%ADMIN ALL='
    line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'
    validate: '/usr/sbin/visudo -cf %s' # 一樣,如果要改sudoers的話,用visudo

上一篇
day24_k8s10_樹莓PI(網路設定),Dashboard,Resource Monitor,Cert Manage,External DNS(工具),Auditing
下一篇
day26_ansible04_modules_pip,mysql_db,mysql_user,wait_for,uri,register,when
系列文
在地端建置Angular+ASP.NET Core的DevOps環境31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言