ansible学习之旅(其它特性)

简介: ansible学习之旅(其它特性)

ansible其它特性

delegate

任务委派简介:将轮到当前主机执行的任务委派给其它主机执行,可以委派给不在当前playbook的hosts列表中的主机

将新建用户的任务委派给ansible并进行免密,之后可以用普通用户操作ansible  

[root@k81 an]# cat delegate1.yaml 
- hosts: web
  vars:
  - user_name: wangwu
  tasks:
  - name: Create user 
    user: 
      name: "{{ user_name }}"
      generate_ssh_key: yes
      ssh_key_bits: 2048
      ssh_key_file: .ssh/id_rsa
    register: user_message  # 注册到变量方便后面使用
    delegate_to: localhost  # 将任务委派给ansible自己
    run_once: true # 委派任务仅执行一次,避免组内多个主机触发多次委派,创建用户多次委派会出现用户已经存在的报错导致后续直接任务failed
  - name: Debug key
    debug: 
      msg: "{{ user_message.ssh_public_key }}" # 检查是否将公钥提取除磷了
  - name: Create ~/.ssh
    file:
      path: ~/.ssh
      state: directory
      mode: "0700"
  - name: Trust
    lineinfile:  # 也可以用copy模块的content
      line: "{{ user_message.ssh_public_key }}"
      dest: .ssh/authorized_keys
# 测试执行
[root@k81 an]# ansible-playbook delegate1.yaml
# 执行完成之后可以切换到 wangwu 用户检测免密是否完成,如果是给普通用户免密的话只需要lineinfile模块的dest修改即可 

可以用委派来将某个被控端的文件拷贝给其它被控端  

[root@k81 an]# cat delegate2.yaml 
- hosts: web
  vars:
  tasks:
  - name: Copy file 
    synchronize:  # 这里用copy模块会报错
      src: /tmp/ansible_test
      dest: /tmp/ansible_test
    delegate_to: c1  # 将任务委派给c1,需要注意的c1要能免密传输,所以需要先在c1上对c3,c4做免密操作,在上一篇部署k8s集群的时候就用到了这个操作
    #run_once: true # 委派任务仅执行一次,避免组内多个主机触发多次委派
[root@k81 an]# ssh c1 touch /tmp/ansible_test
[root@k81 an]# ansible-playbook delegate2.yaml 
 ____________
< PLAY [web] >
 ------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
 __________________
< TASK [Copy file] >
 ------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
changed: [c4 -> c1]
changed: [c3 -> c1]
 ____________
< PLAY RECAP >
 ------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
c3                         : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
c4                         : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
[root@k81 an]# ansible web -a 'ls /tmp/ansible_test'
c4 | CHANGED | rc=0 >>
/tmp/ansible_test
c3 | CHANGED | rc=0 >>
/tmp/ansible_test
## 检测是否成功  


Vault

Ansible Vault概述:


Ansible Vault 可以将敏感的数据文件进行加密,而非存放在明文的playbooks 中;比如: 部分playbook内容中有明文密码信息,可以对其进行加密操作;后期只有输入对应的密码才可以查看、编辑或执行该文件,如没有密码则无法正常运行。


加密  

[root@k81 an]# echo "hello world" > hello.yaml
[root@k81 an]# ansible-vault encrypt hello.yaml 
New Vault password: 
Confirm New Vault password: 
Encryption successful
[root@k81 an]# cat hello.yaml 
$ANSIBLE_VAULT;1.1;AES256
37643964373832316261343139643962323535363561313665333833363766373932353938333137
3062646334346139353838376231383232643032663333350a393833633337633363303735373661
37663039663738373337613264613536336536353630613035376634353937346264353937316138
3239323737663066660a346237343762353064396564663837303131343232343836336633613263
3135
## 加密之后查看、修改文件需要输入密码
[root@k81 an]# ansible-vault view hello.yaml 
Vault password: 
hello world
[root@k81 an]# ansible-vault edit hello.yaml 
Vault password: 
[root@k81 an]# ansible-vault view hello.yaml 
Vault password: 
hello world
hello world
hello world
hello world  
  • 修改密码
[root@k81 an]# ansible-vault rekey hello.yaml 
Vault password: 
New Vault password: 
Confirm New Vault password: 
Rekey successful
  • 将密码存放于文件中
[root@k81 an]# echo 2 > pass_file
[root@k81 an]# ansible-vault view hello.yaml --vault-password-file=pass_file 
hello world
hello world
hello world
hello world
## 每次都指定文件有点麻烦,那我们可以去修改ansible.cfg里面的配置
#vault_password_file =
# 将注释打开之后备注上密码文件的路径,以后就不需要 --vault-password-file 指定了
  • 移除密码
[root@k81 an]# ansible-vault decrypt hello.yaml 
Vault password: 
Decryption successful
[root@k81 an]# cat hello.yaml 
hello world
hello world
hello world
hello world  


roles

Roles 是组织 PLaybook 最好的一种方式,它基于一个已知的文件结构,去自动的加载 vars,tasks 以及 handlers 以便playbook 更好的调用。 roles 相比playbook 的结构更加的清晰有层次,但 roles 要比 playbook 稍微麻烦一些;

安装任何软件都需要先安装时间同步服务,那么每个 playbook都要编写时间同步服务的 task ,会显得整个配置比较臃肿,且难以维护,如果使用Role: 我们则可以将时间同步服务 task 任务编写好,等到需要使用的时候进行调用就行了,减少重复编写task带来的文件臃肿


查询哪些roles可用

[root@k81 an]# ansible-galaxy list
# /etc/ansible/roles
# /an 

其定义位置在 ansible.cfg中

roles_path    = /etc/ansible/roles  # 默认指定路径是/etc/ansible/roles
如需要加路径可可以在后面接 :./roles 


roles的目录结构

Roles 是组织 PLaybook 最好的一种方式,它基于一个已知的文件结构,去自动的加载 vars,tasks 以及 handlers 以便playbook 更好的调用。 roles 相比playbook 的结构更加的清晰有层次,但 roles 要比 playbook 稍微麻烦一些;

安装任何软件都需要先安装时间同步服务,那么每个 playbook都要编写时间同步服务的 task ,会显得整个配置比较臃肿,且难以维护,如果使用Role: 我们则可以将时间同步服务 task 任务编写好,等到需要使用的时候进行调用就行了,减少重复编写task带来的文件臃肿


查询哪些roles可用

[root@k81 an]# ansible-galaxy list
# /etc/ansible/roles
# /an  

其定义位置在 ansible.cfg中

roles_path    = /etc/ansible/roles  # 默认指定路径是/etc/ansible/roles
如需要加路径可可以在后面接 :./roles 


roles的目录结构

[root@k81 an]# ansible-galaxy  init test  # 这个命令可以自动初始化一个role的文件夹
- Role test was created successfully
[root@k81 an]# tree test
test
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars 

在Ansible中,一个Role通常包含以下文件和目录:

tasks:定义Role的主要执行任务。

handlers:定义处理程序,当某个任务发生变化时,执行处理程序。

files:包含将复制到目标主机的文件。

templates:包含将复制到目标主机并根据变量进行渲染的模板文件。

vars:包含变量文件,这些变量将用于Role。

defaults:包含默认变量,如果没有定义相应变量,则将使用这些变量。

meta:定义Role的元数据,包括作者、描述、依赖项等信息。

tests:包含Role的测试脚本。


其中,tasks和handlers是必须的,其他目录和文件是可选的,它们根据Role的具体需求进行添加和配置。

RoLes依赖关系
roles 允许在使用时自动引入其他 role, role 依赖关系存储在meta/main.yml 文件中
例如: 安装wordpress 项目时:o
1.需要先确保 nginx 与 php-fpm 的 role 都能正常运行
2.然后在wordpress的 role 中定义,依赖关系3.依赖的 role 有 nginx 以及 php-fpm
#wordpress依赖nginx与php-fpm的role
[root@k81 playbook]# cat/root/roles/wordpress/meta/main.yml
---
dependencies:
- { role: nginx }
- { role: php-fpm }
wordpress 的 role 会先执行 nginx、php-fpm 的 role
最后在执行 wordpress 本身  


roles调用

roles也需要playbook去调用的,调用role的playbook如下  

[root@k81 an]# cat k8s_kubeadm/kubeadm.yaml 
---
- hosts: all
  vars:
    local_network:  10.10.21.0/24  
    Service_CIDR: 172.16.0.0/16    
    Pod_CIDR: 192.168.0.0/16      
    HA_Domain: myk8s             
    HA_IP: 10.10.21.196          
    host_passwd: zt   
  roles:
  - initial
  - chrony
  - kernel
  - containers
  - container_init

一个简单的nfs的role

先写角色

[root@k81 an]# ansible-galaxy role init nfs-server
[root@k81 an]# cat nfs-server/templates/exports.j2   # 给nfs准备的配置文件
{{ share_dir }} {{ share_ip }} (rw,sync,all_squash,anonuid={{ nfs_uid }},anongid={{ nfs_uid }})
[root@k81 an]# cat  nfs-server/tasks/main.yml   # 角色核心任务
---
# tasks file for nfs-server
- name: Install nfs
  yum: name=nfs-utils
- name: Configure nfs
  template: src=exports.j2 dest=/etc/exports
  notify: Restart nfs
- name: Create group
  group: name={{ nfs_group }} gid={{ nfs_gid }}
- name: Create user
  user: name={{ nfs_user }} uid={{ nfs_uid }} group={{ nfs_group }} password="{{ nfs_passwd | password_hash('sha512') }}" create_home=no shell=/sbin/nologin
- name: Create Directory
  file: path={{ share_dir }} state=directory owner={{ nfs_user }}  group={{ nfs_group }}   mode="0755"
- name: Start nfs
  systemd: name=nfs state=started enabled=yes
[root@k81 an]# cat nfs-server/handlers/main.yml   # handlers,每次更新配置之后重启nfs
---
# handlers file for nfs-server
- name: Restart nfs
  systemd: name=nfs state=restarted
[root@k81 an]# cat nfs-server/vars/main.yml   # 角色的变量定义
---
# vars file for nfs-server
share_dir: /data
share_ip: 10.10.21.0/24
nfs_uid: 666
nfs_gid: 666
nfs_user: nfs1
nfs_passwd: nfs1
nfs_group: nfs1

写剧本尝试调用

[root@k81 an]# cat nfs1.yaml 
- hosts: nfs
  roles:
  - nfs-server
[root@k81 an]# ansible-playbook nfs1.yaml
## 待任务全部ok之后检查是否完成
[root@k81 an]# showmount -e c5
Export list for c5:
/data (everyone)
[root@k81 an]# showmount -v c5
showmount for 1.3.0
[root@k81 an]# mount -t nfs c5:/data /mnt

一个简单memcache的role

编辑角色

[root@k81 an]# ansible-galaxy role init memcache
[root@k81 an]# cat memcache/tasks/main.yml 
---
# tasks file for memcache
- name: Install memcache
  yum: name=memcached
- name: Copy config file
  template: src=memcached.j2 dest=/etc/sysconfig/memcached
  notify: Restart memcached
- name: Start memcached
  systemd: name=memcached state=started enabled=yes
[root@k81 an]# cat memcache/handlers/main.yml 
---
# handlers file for memcache
- name: Restart memcached
  systemd: name=memcached state=restarted
[root@k81 an]# cat memcache/templates/memcached.j2 
PORT=11211
USER="memcached"
MAXCONN="{{ ansible_memtotal_mb // 4 }}"  # 被控端可用内存除以 4
CACHESIZE="64"
OPTIONS=""  

编辑剧本尝试调用

[root@k81 an]# cat mem1.yaml 
- hosts: nfs
  remote_user: root
  roles:
  - memcache
[root@k81 an]# ansible-playbook mem1.yaml 
## 检查是否成功
[root@k81 an]# ansible nfs -m shell -a 'systemctl status memcached -l'
c5 | CHANGED | rc=0 >>
● memcached.service - Memcached
   Loaded: loaded (/usr/lib/systemd/system/memcached.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2023-04-27 16:52:55 CST; 11min ago
 Main PID: 46828 (memcached)
    Tasks: 6
   CGroup: /system.slice/memcached.service
           └─46828 /usr/bin/memcached -u memcached -p 11211 -m 64 -c 942
Apr 27 16:52:55 c5 systemd[1]: Started Memcached.
[root@k81 an]# ansible nfs -m shell -a 'cat /etc/sysconfig/memcached '
c5 | CHANGED | rc=0 >>
PORT=11211
USER="memcached"
MAXCONN="942"
CACHESIZE="64"
OPTIONS=""


目录
相关文章
|
7月前
|
运维 关系型数据库 Shell
小白带你学习linux自动化运维ansible
小白带你学习linux自动化运维ansible
197 0
小白带你学习linux自动化运维ansible
|
Shell 网络安全 开发工具
|
运维 网络安全 数据安全/隐私保护
ansible学习之旅(入门篇)
ansible学习之旅(入门篇)
416 0
|
应用服务中间件 网络安全 开发工具
学习ansible常用模块这篇就够了(剧本)(二)
学习ansible常用模块这篇就够了(剧本)
116 0
|
运维 应用服务中间件 Shell
学习ansible常用模块这篇就够了(剧本)(一)
学习ansible常用模块这篇就够了(剧本)
229 0
|
运维 Shell 网络安全
|
Kubernetes 负载均衡 Docker
ansible学习之旅(ansible依托kubeadm安装一个简单的k8s集群)
ansible学习之旅(ansible依托kubeadm安装一个简单的k8s集群)
130 0
|
存储 JSON 缓存
ansible学习之旅(facts变量)
ansible学习之旅(facts变量)
144 0
ansible学习之旅(初识变量)
ansible学习之旅(初识变量)
69 0
ansible学习之旅(初识play-book)
ansible学习之旅(初识play-book)
119 0