安装ansible
[root@jenkins ~]#apt update && apt -y install ansible
默认没有配置文件
[root@jenkins ~]#ansible --version
ansible 2.10.8
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 3.10.12 (main, Jul 29 2024, 16:56:48) [GCC 11.4.0]
[root@jenkins ~]#mkdir -p /etc/ansible/ && touch /etc/ansible/ansible.cfg
[root@jenkins ~]#ansible --version
ansible 2.10.8
config file = /etc/ansible/ansible.cfg
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 3.10.12 (main, Jul 29 2024, 16:56:48) [GCC 11.4.0]
准备主机清单文件
默认是以jenkis用户身份运行,需要指定以root身份运行
[root@jenkins ~]#vim /etc/ansible/hosts
[webservers]
10.0.0.201 ansible_ssh_user=root
[appservers]
10.0.0.202 ansible_ssh_user=root
打通key验证
[root@jenkins ~]#su - jenkins
jenkins@jenkins:~$ ssh-keygen
jenkins@jenkins:~$ ssh-copy-id root@10.0.0.201
jenkins@jenkins:~$ ssh-copy-id root@10.0.0.202
jenkins@jenkins:~$ ansible all -u root -m ping
10.0.0.201 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
10.0.0.202 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
安装
Ansible
插件
准备两个不同环境的主机清单文件
需要打通jenkis用户上面的rootkey验证
[root@jenkins ansible]#cat /etc/ansible/hosts_product
[webservers]
10.0.0.201
10.0.0.202
[root@jenkins ansible]#cat /etc/ansible/hosts_test
[webservers]
10.0.0.203
10.0.0.204
准备
Playbook
文件
[root@jenkins ~]#vim /data/ansible/test.yml
---
- hosts: webservers
remote_user: root
tasks:
- name: Execute command
shell:
cmd: hostname -I
register: result
- name: Show result
debug:
msg: "{{ result.stdout }}"
hosts:
指定要执行此 playbook 的目标主机组。在这个例子中,目标主机组为 webservers。
remote_user:
指定远程主机上的用户。这里使用的是 root 用户。
tasks:
定义了一系列要执行的任务。
- name: Execute command:
任务名称,用于描述此任务的功能。
使用 shell 模块执行命令 hostname -I。
register 选项将命令的输出结果保存到变量 result 中。
- name: Show result:
任务名称,用于描述此任务的功能。
使用 debug 模块打印出 result 变量的内容。
创建参数化任务
执行不同任务输出不同
使用
Ansible Playbook
实现向
Playbook
中传参功能
创建主机清单文件
[root@jenkins ~]#cat /etc/ansible/hosts_test
[webservers]
10.0.0.203
[appservers]
10.0.0.204
[root@jenkins ~]#cat /etc/ansible/hosts_product
[webservers]
10.0.0.201
[appservers]
10.0.0.202
编写
Playbook
文件
[root@jenkins ~]#cat /data/ansible/test.yml
---
- hosts: "{{ ansible_hosts }}"
remote_user: root
tasks:
- name: Execute command
shell:
cmd: hostname -I
register: result
- name: Show result
debug:
msg: "{{ result.stdout }}"
配置任务
这里的值是host_list
多出了选项,可以根据选项传参数