[DO374] Ansible 配置文件
- 1. 配置文件位置
- 2. 配置文件
- 3. Ansible 配置
- 4. Ansible的Ad-hoc
- 5. Ansible 模块
- 6. playbook段落
- 7. 任务执行后续
- 8. Ansible 变量
- 8.1 ansible 变量的定义
- 8.1.1 主机变量
- 8.1.2 主机组变量
- 8.2 vars的循环
- 9. Ansible Collection
- 10. Ansible-galaxy 安装模块
- 10.1 红帽和ansible的hub配置
- 10.2 私有化hub配置
- 11. 剧本执行顺序
- 12. 判断
- 12.1 远程文件的判断
- 12.2 字符串大小写的判断
- 12.3 判断ansible版本(控制端)
- 12.4 子集
- 12.5 父集(超集)
- 12.6 判断字符串是否在集合内
- 12.7 多任务用同一条件判断
- 12.7.1 block
- 12.7.2 rescue
- 12.7.3 always
- 12.7.4 剧本退出
- 12.7.5 带有条件的退出
- 13. 循环语句
- 13.1 遍历列表
- 13.2 遍历字典
- 13.3 loop循环
- 14. 任务委派
- 15. 事实委派
- 16. 缓存事实变量
1. 配置文件位置
- 默认位置(全局)/etc/ansible/ansible.cfg
- 当前工作目录./ansible.cfg
- 当前用户家目录下的~/.ansible.cfg
- 当前系统的ANSIBLE_CONFIG环境变量
优先级顺序: 4 > 2 > 3 > 1
2. 配置文件
配置块 | 含义 |
---|---|
[defaults] | 通用配置项,配置远程用户,连接密码,文件清单位置等 |
[inventory] | 主机清单段落,配置清单使用的插件等 |
[privilege_escalation] | 提权配置,是否提权,提权到哪个用户 |
[persistent_connection] | RHEL6 连接插件,现在默认ssh连接 |
[ssh_connection] | SSH连接配置项 |
[persistent_connection] | 持久连接配置项,连接超时时间,命令超时时间 |
[accelerate] | 加速项,默认端口:5099 |
[selinux] | selinux的配置项,用来配置ansible支持的文件系统驱动及lxc容器配置 |
[colors] | 配置ansible的颜色,定义执行成功,错误输出的颜色 |
[diff] | 打印任务执行前后的差异 |
3. Ansible 配置
如果使用普通用户进行sudo,客户端需要
# 1. add user
useradd qiu
# 2. Set a passwd to the qiu user
echo redhat | passwd --stdin qiu
# 3. Grant sudo privileges to the qiu user
vim /etc/sudoers.d/qiu
qiu ALL=(ALL) NOPASSWD:ALL
ansible.cfg 配置
[defaults]
inventory=./inventory # 清单文件
remote_user = root # 远程用户
ask_pass = false # 连接是用 密码/秘钥
[privilege_escalation]
become=True # 是否提权
become_method=sudo # 是否 sudo
become_user=root # 提权到 root 用户
become_ask_pass=False # 提权是否需要 密码
[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s # ssh 连接加速
通过命令添加
# Set passwd file.
echo "Asimov" > .ansible_pass
chmod 600 .ansible_pass
# Test whether the password can be used for connection.
ansible all -m shell -a "whoami" -u root --vault-pass-file .ansible_pass
# Create qiu user.
ansible all -m shell -u root --vault-pass-file .ansible_pass -a "useradd qiu"
# Grant a password to the qiu user.
ansible all -m shell -u root --vault-pass-file .ansible_pass -a "echo 'root123' qiu"
# Grant sudo privileges to the qiu user.
ansible all -m shell -u root --vault-pass-file .ansible_pass -a "echo 'qiu ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/qiu"
# Grant access key to the qiu user.
ansible all -m shell -u root --vault-pass-file .ansible_pass -a "mkdir /home/qiu/.ssh;echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDGtUW3ismHyuCW4CDdTVOOOq6aySdtYenXFWWx7HJa4VTepkG00aaLId9ocra10hc+MB0GTJMCyabDv3i8NKdi6GDH/aOLVsp/Ewy8DEzZMBlJDCt4v2i4/wU4liw6KgEFkZs+5hnqU8d4QzldyGJ5onr+AGvFOKG68CS0BBl40Z1twf1HhCyx8k6nzD2ovlkxWRFZKPAFrtPCBVvQDkOfVFZF+lwzaSztgAjbFZ4A9jqQyUYx4kOJ5DtRef36ucdUdVQale0+8lICl7/gb142SPpYfhxe88/BJScLPRjvVNeu1TxRmoHtVazqnAoRxQYAn2MoI6AG+w6QuZf8f7aL LabGradingKey' >> /home/qiu/.ssh/authorized_keys;chmod 600 /home/qiu/.ssh/authorized_keys; chown -R qiu:qiu /home/qiu/.ssh"
# Try to use the qiu remote user to connect with ansible.
# Modify ansible.cfg and change remote_user to qiu user.
ansible all -m ping
4. Ansible的Ad-hoc
ad-hoc: ansible 临时命令,用ansible的模块来完成自动化任务,每次只能使用1个模块,来完成一个任务.因此ad-hoc称为ansible的临时命令
ad-hoc的语法:
格式: ansible 选择的主机 -m [模块] -a “模块的参数” (ansible参数)
# example
ansible all -m shell -a "whoami" -u root -k
5. Ansible 模块
模块查询方式:
ansible-doc -l: 列出当前支持的所有模块
- 命令模块:
模块名 | 作用 |
---|---|
shell | 相当于在被控端本机上执行linux指令 |
command | 相当于在被控端本机上执行linux指令,但有4个符号除外 |,>,<,& 出现这4个符号时,command将无法执行该命令 |
script | 将主控端的shell复制到远程并执行. |
raw | 不支持高阶参数(chdir,creates,removes) |
chdir 执行命令前修改执行路径
creates 判断文件是否存在,如果存在就不执行后面的命令,文件不存在则执行后续命令
removes 和creates相反
当ansible省略模块时,默认使用command模块,取决于ansible.cfg配置文件中module_name = command参数.
- 文件模块
6. playbook段落
target段落:
hosts: 定义play在那些主机上运行
remote_user: 定义运行play的远程用户是哪个
gather_facts: 定义是否收集事实变量
注意: 在target中定义的参数可以是ansible.cfg中出现的,如果play中没有定义,则按ansible.cfg中的为准
vars段落: 用来定义变量,如果没有可以省略
支持在该段落中定义变量,也支持从文件中引入变量
直接定义变量:
变量名1: 值1
变量名2: 值2
tasks段落 用来定义任务,可以省略
在playbook中默认存在一个facts的任务.可以通过target中的gather_facts: false关闭
tasks:
- name: 任务名称
模块名称:
具体参数: 参数的值
7. 任务执行后续
当需要执行完一个模块后有后续动作,可以用notify通知handlers.
当一个notify需要调用多个handler时,使用listen来关联监听.
---
- name: test notify
hosts: servera.lab.example.com
gather_facts: false
tasks:
- name: touch file
ansible.builtin.file:
path: /etc/foo.conf
state: touch
notify: show debug info
handlers:
- name: handler 1
listen: show file
ansible.builtin.debug:
msg: "in 1"
- name: handler 2
listen: show file
ansible.builtin.debug:
msg: "in 2"
- name: handler 3
listen: show file
ansible.builtin.debug:
msg: "in 3"
8. Ansible 变量
8.1 ansible 变量的定义
# inventory
servera ansible_port=2222 ansible_host=192.168.31.123 ansible_user=devlop
serverb ansible_port=4422 ansible_host=192.168.31.124 ansible_user=test
变量 | 含义 |
---|---|
ansible_port | ssh端口 |
ansible_host | 服务器ip |
ansible_user | ssh用户 |
ansible_connection | ssh连接类型:local,ssh,paramikko,默认ssh |
ansible_ssh_pass | ssh 密码 |
ansible_ssh_privite_key_file | ssh秘钥文件路径 |
ansible_ssh_executable | ssh命令路径 |
8.1.1 主机变量
对单个主机自定义变量
[test]
serverd.lab.example.com app=apache
servere.lab.example.com app=vsftpd
8.1.2 主机组变量
对组进行定例变量
[test]
serverd.lab.example.com app=apache
servere.lab.example.com app=vsftpd
[test:vars]
zabbix_agent=yes
prometheus_agent=no
主机的vars优先级高于主机组中的vars
8.2 vars的循环
---
- name: test notify
hosts: servera.lab.example.com
gather_facts: false
vars:
os_version:
redhat:
release: '7.9'
ubuntu:
release: '20.04'
openeuler:
release: '24.03LTS'
tasks:
- name: print versions
debug:
msg: "{{ item.value.release }}"
loop: "{{ os_version | dict2items }}"
9. Ansible Collection
- 通过红帽自动化中心获取
https://console.redhat.com/ansible/automation-hub
- 通过ansible galaxy来获取
https://galaxy.ansible.com/ui/
- 通过yaml安装
# collection.yml
collections:
- name: url
执行命令进行安装
ansible-galaxy collection install -r collection.yml -p 安装的路径和位置
10. Ansible-galaxy 安装模块
10.1 红帽和ansible的hub配置
[defaults]
ask_pass=False
forks=5
inventory=./inventory
remote_user = devops
collections_path=/root/collections
[privilege_escalation]
become_method=sudo
become_user=root
become_ask_pass=False
become=true
[galaxy]
server_list=redhat_hub
[galaxy_server.redhat_hub]
url=https://console.redhat.com/api/automation-hub/content/published/
auth_url=https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token
token=eyJhbGciOiJIUzUxMiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI0NzQzYTkzMC03YmJiLTRkZGQtOTgzMS00ODcxNGRlZDc0YjUifQ.eyJpYXQiOjE3MzYzMTg4MzMsImp0aSI6ImI0YjJmZTAxLWM5NWMtNDZiNS05YWE4LWRlZGQyZmE1Y2RiNCIsImlzcyI6Imh0dHBzOi8vc3NvLnJlZGhhdC5jb20vYXV0aC9yZWFsbXMvcmVkaGF0LWV4dGVybmFsIiwiYXVkIjoiaHR0cHM6Ly9zc28ucmVkaGF0LmNvbS9hdXRoL3JlYWxtcy9yZWRoYXQtZXh0ZXJuYWwiLCJzdWIiOiJmOjUyOGQ3NmZmLWY3MDgtNDNlZC04Y2Q1LWZlMTZmNGZlMGNlNjoxMzkxNzA5OTMyMkAxMzkuY29tIiwidHlwIjoiT2ZmbGluZSIsImF6cCI6ImNsb3VkLXNlcnZpY2VzIiwibm9uY2UiOiIwYzYyMDFkZS03MmE4LTRhNDEtOTE3My1mOGMwNzgxYjBmNzQiLCJzaWQiOiJiZTA0ZTk1Zi1iZjViLTRhZTgtOGJhMS05MjBjMzk5NjQxZGYiLCJzY29wZSI6Im9wZW5pZCBiYXNpYyBhcGkuaWFtLnNlcnZpY2VfYWNjb3VudHMgcm9sZXMgd2ViLW9yaWdpbnMgY2xpZW50X3R5cGUucHJlX2tjMjUgb2ZmbGluZV9hY2Nlc3MifQ.QdBlhVTGUj0Z0IsAkSRXM5yR2FfnY8k0Sczj5xVUjaKCiTJ-lCk08dUP2Omcndk6oQ0LYPXDzWL7v4f9423trg
测试安装ansible.posix
ansible-galaxy collection install ansible.posix
确认安装完成
[root@foundation0 ansible]# ls /root/collections/ansible_collections/ansible
posix
添加ansible仓库
[galaxy]
# 下行追加ansible_hub定义
server_list=redhat_hub,ansible_hub
[galaxy_server.redhat_hub]
url=https://console.redhat.com/api/automation-hub/content/published/
auth_url=https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token
token=eyJhbGciOiJIUzUxMiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI0NzQzYTkzMC03YmJiLTRkZGQtOTgzMS00ODcxNGRlZDc0YjUifQ.eyJpYXQiOjE3MzYzMTg4MzMsImp0aSI6ImI0YjJmZTAxLWM5NWMtNDZiNS05YWE4LWRlZGQyZmE1Y2RiNCIsImlzcyI6Imh0dHBzOi8vc3NvLnJlZGhhdC5jb20vYXV0aC9yZWFsbXMvcmVkaGF0LWV4dGVybmFsIiwiYXVkIjoiaHR0cHM6Ly9zc28ucmVkaGF0LmNvbS9hdXRoL3JlYWxtcy9yZWRoYXQtZXh0ZXJuYWwiLCJzdWIiOiJmOjUyOGQ3NmZmLWY3MDgtNDNlZC04Y2Q1LWZlMTZmNGZlMGNlNjoxMzkxNzA5OTMyMkAxMzkuY29tIiwidHlwIjoiT2ZmbGluZSIsImF6cCI6ImNsb3VkLXNlcnZpY2VzIiwibm9uY2UiOiIwYzYyMDFkZS03MmE4LTRhNDEtOTE3My1mOGMwNzgxYjBmNzQiLCJzaWQiOiJiZTA0ZTk1Zi1iZjViLTRhZTgtOGJhMS05MjBjMzk5NjQxZGYiLCJzY29wZSI6Im9wZW5pZCBiYXNpYyBhcGkuaWFtLnNlcnZpY2VfYWNjb3VudHMgcm9sZXMgd2ViLW9yaWdpbnMgY2xpZW50X3R5cGUucHJlX2tjMjUgb2ZmbGluZV9hY2Nlc3MifQ.QdBlhVTGUj0Z0IsAkSRXM5yR2FfnY8k0Sczj5xVUjaKCiTJ-lCk08dUP2Omcndk6oQ0LYPXDzWL7v4f9423trg
# 添加以下2行
[galaxy_server.ansible_hub]
url=galaxy.ansible.com
安装一个vmware.vmware的插件
ansible-galaxy collection install vmware.vmware
安装结束后可以看到在/root/collections/ansible_collections/创建了vmware的子目录,我们下载的新插件就安装在这个位置
10.2 私有化hub配置
复制仓库配置
[galaxy]
server_list = community_repo
[galaxy_server.community_repo]
url=https://hub.lab.example.com/api/galaxy/content/community/
token=<put your token here>
生成token
修改后的ansible.cfg文件内容
[defaults]
collections_path=/home/student/collection/plugin
[galaxy]
server_list = community_repo
[galaxy_server.community_repo]
url=https://hub.lab.example.com/api/galaxy/content/community/
token=9e266577135f4a42c8612d4bb06a9dcbdb394cdc
创建galaxy collection的路径
mkdir -p /home/student/collection/plugin
安装一个community库的试一下
复制以下命令在命令行执行
11. 剧本执行顺序
- pre_tasks
- pre_tasks中的handler
- roles
- tasks
- roles中的handler
- post_tasks
- post_tasks中的handler
- pre roles和tasks post
12. 判断
12.1 远程文件的判断
---
- name: Is the file in servera
hosts: servera.lab.example.com
gather_facts: false
tasks:
- name: get file status
file:
name: /etc/hosts
state: file
register: get_file
- name: get file
debug:
msg: "The file is exists"
when: get_file.state == "file"
12.2 字符串大小写的判断
---
- name: Is the file in servera
hosts: servera.lab.example.com
gather_facts: false
vars:
uppercase: REDHAT
lowercase: redhat
tasks:
- name: Uppercase output
debug:
msg: "It's Uppercase!"
when: uppercase is upper
- name: Lowercase output
debug:
msg: "It's Lowercase!"
when: lowercase is lower
12.3 判断ansible版本(控制端)
---
- name: Is the file in servera
hosts: servera.lab.example.com
gather_facts: false
tasks:
- name: Operating Version
debug:
msg: "The playbook can run."
when: ansible_version.full is version("2.8","gt")
12.4 子集
---
- name: Is the file in servera
hosts: servera.lab.example.com
gather_facts: false
vars:
os_type:
- rhel
- fedora
- centos
- ubuntu
- openeuler
redhat:
- rhel
- fedora
- centos
tasks:
- name: Subset
debug:
msg: "It's subset"
when: redhat is subset(os_type)
12.5 父集(超集)
---
- name: Is the file in servera
hosts: servera.lab.example.com
gather_facts: false
vars:
os_type:
- rhel
- fedora
- centos
- ubuntu
- openeuler
redhat:
- rhel
- fedora
- centos
tasks:
- name: SuperSet
debug:
msg: "It's superset"
when: os_type is superset(redhat)
12.6 判断字符串是否在集合内
---
- name: Is the file in servera
hosts: servera.lab.example.com
gather_facts: false
vars:
os_type:
- rhel
- fedora
- centos
- ubuntu
- openeuler
redhat:
- rhel
- fedora
- centos
centos: centos
tasks:
- name: SuperSet
debug:
msg: "It's in superset"
when: centos in redhat
12.7 多任务用同一条件判断
12.7.1 block
block: 将多个任务包含在一个区块内,进行判断.
---
- name: block message test
hosts: all
gather_facts: true
tasks:
- name: in block
block:
- name: debug1
debug:
msg: "msg 1"
- name: debug2
debug:
msg: "msg 2"
- name: debug3
debug:
msg: "msg 3"
- name: debug4
debug:
msg: "msg 4"
- name: display hostname
debug:
var: ansible_hostname
when: ansible_hostname == "servera"
这样就不需要在每个模块下面都加一个重复的
when: ansible_hostname == "servera"
12.7.2 rescue
rescue是用来处理block失败的后续手段.
---
- name: block message test
hosts: all
gather_facts: true
tasks:
- name: in block
block:
- name: get file
file:
name: /opt/rh374.txt
state: file
rescue:
- name: touch file
file:
name: /opt/rh374.txt
state: touch
当block内容执行错误后,rescue的修复任务被触发.如果block执行正常,那么rescue内容不会被执行.
当第二次再次执行,修复任务不在被执行
12.7.3 always
无论如何这个命令都会被执行
---
- name: block message test
hosts: all
gather_facts: true
tasks:
- name: in block
block:
- name: get file
file:
name: /opt/rh374.txt
state: file
rescue:
- name: touch file
file:
name: /opt/rh374.txt
state: touch
always:
- name: show the filename rh374.txt
file:
name: /opt/rh374.txt
state: file
12.7.4 剧本退出
---
- name: block message test
hosts: servera.lab.example.com
gather_facts: true
tasks:
- name: get file
file:
name: /etc/hosts
state: file
- name: exit playbook
fail:
msg: "exit playbook"
- name: output message
debug:
msg: "I am running"
当执行到fail段落时候就直接退出了,后续任务不会再被执行
判断ansible版本是否高于2.9,如果太低那么就不执行
---
- name: block message test
hosts: servera.lab.example.com
gather_facts: true
tasks:
- name: output message
debug:
msg: "{{ ansible_version.full }}"
- name: optput ansible version
fail:
msg: "The ansible version is lower than 2.9,you must update the ansible version."
when: ansible_version.full is version("2.9","lt")
- name: install applications
debug:
msg: "install apps....."
12.7.5 带有条件的退出
当条件触发,则退出
---
- name: block message test
hosts: servera.lab.example.com
gather_facts: true
tasks:
- name: Determine the ansible version,then install applications
debug:
msg: "Install apps....."
failed_when: ansible_version.full is version("2.9","lt")
改为failed_when之后可以将2-3个task合并成一个
13. 循环语句
13.1 遍历列表
在ansible中有很多循环场景需要批量安装或者授权.
---
- name: loop
hosts: servera.lab.example.com
gather_facts: true
vars:
user_list:
- tom
- bob
- andy
- tony
- ted
tasks:
- name: Add users
user:
name: "{{ item }}"
state: present
with_items: "{{ user_list }}"
13.2 遍历字典
---
- name: loop
hosts: servera.lab.example.com
gather_facts: true
vars:
user_list:
ituser1:
name: tom
uid: 3000
home: /home/tom
ituser2:
name: jarry
uid: 3001
home: /home/jarry
tasks:
- name: Add users
#debug:
# msg: "{{ item.value.name }} {{ item.value.uid }} {{ item.value.home }}"
#msg: "{{ item.value.name }}"
user:
name: "{{ item.value.name }}"
uid: "{{ item.value.uid }}"
comment: "{{ item.value.name }}"
home: "{{ item.value.home }}"
with_dict: "{{ user_list }}"
到servera上确认两个用户正常创建
13.3 loop循环
loop本身是循环列表,可以通过loop dict2items来循环字典.将字典转换成列表.
---
- name: loop
hosts: servera.lab.example.com
gather_facts: true
vars:
user_list:
ituser1:
name: tom
uid: 3000
home: /home/tom
ituser2:
name: jarry
uid: 3001
home: /home/jarry
tasks:
- name: Add users
debug:
msg: "{{ item.value.name }} {{ item.value.uid }} {{ item.value.home }}"
loop: "{{ user_list |dict2items }}"
14. 任务委派
delegate_to 可以将任务交给其他服务器执行,此服务器甚至可以不在inventory中
---
- name: delegate to pluging
hosts: servera,serverb
gather_facts: true
tasks:
- name: Delegate the playbook to serverc.
block:
- name: Install Apache
yum:
name: httpd
state: present
- name: Make sure a service unit is running
ansible.builtin.systemd:
state: started
name: httpd
enabled: yes
- name: Make sure a service unit is stopping
ansible.builtin.systemd:
state: stopped
name: firewalld
enabled: yes
- name: Create the index file
copy:
dest: /var/www/html/index.html
content: "In serverc"
delegate_to: serverc
- name: Download the file
ansible.builtin.get_url:
url: http://serverc/index.html
dest: /root/aaa.html
将整个block中内容由servera和serverb调度给serverc,在serverc完成了调度后,servera和serverb再从serverc上获取到该文件
15. 事实委派
主要作用就是在服务器之间的参数传递
一般delegate_facts和delegate_to 会同时出现
---
- name: Delegate facts
hosts: servera,serverb
gather_facts: no
tasks:
- name: get servera facts
setup:
delegate_facts: true
delegate_to: serverb
- name: set ip info
copy:
dest: /opt/ipaddress.txt
content: "{{ hostvars['serverb'].ansible_eth0.ipv4.address }}"
16. 缓存事实变量
缓存事实变量目的: 为了加速playbook的执行加速,不必每次运行playbook都要进行实时变量的收集.
常见有3种缓存方式:
- jsonfile
- memcache
- redis
开启缓存方式:
在ansible.cfg中[defaults]段落中gathering= 进行设置
参数 | 含义 |
---|---|
smart | 智能收集,如果本地有缓存则使用缓存,如果本地没有缓存则收集事实变量并缓存. |
implicit | 一直收集事实变量(默认) |
explict | 从来不收集,除非在playbook中指定gather_facts=true |
smart开启后需要指定以下参数:
参数 | 值 | 含义 |
---|---|---|
fact_caching= | jsonfile/memcached/redis三选一 | 以哪种格式缓存 |
fact_cacheing_connection | ./facts_cache/ | jsonfile需要指定事实变量缓存的位置 |
fact_caching_timeout | 86400 (一天) | 当缓存失效后,重新开始缓存 |
memcache配置参数:
参数 | 值 | 含义 |
---|---|---|
fact_caching | memcached | 使用memcache来做缓存 |
fact_caching_connection | 127.0.0.1:11211 | memcache的地址 |