ansible部署jdk示例

一、准备工作

1.1 安装ansible
yum -y install tree ansible
1.2 初始化
[root@elk01 ~]# mkdir ansible-playbook;cd ansible-playbook
[root@elk01 ~]# ansible-galaxy init jdk
[root@elk01 ansible-playbook]# tree -L 3
.
└── jdk
    ├── ansible.cfg
    ├── files
    │   └── jdk-8u241-linux-x64.tar.gz
    ├── hosts
    ├── install-jdk.yml
    ├── meta
    │   └── main.yml
    ├── tasks
    │   └── main.yml
    └── templates
[root@elk01 ansible-playbook]# touch {hosts,install-jdk.yml,ansible.cfg}
1.3 生成密钥
[root@elk01 jdk]# ssh-keygen
1.4 定义配置
[root@elk01 scripts]# vim ansible.cfg 
[defaults]
inventory = /etc/ansible/hosts
forks = 5
sudo_user = root
remote_port = 22
host_key_checking = False
timeout = 10
log_path = /var/log/ansible.log
roles_path = .
command_warnings=False
module_lang  = zh_CN.UTF-8
module_set_locale = True
1.5 定义主机
[root@elk01 scripts]# vim hosts 
[jdk]
10.0.0.11
10.0.0.12

[jdk:vars]
ansible_ssh_user="root"
ansible_ssh_pass="123123"
ansible_ssh_port="22"

二、编写剧本

2.1 角色文件
[root@elk01 ansible-playbook]# cat install-jdk.yml
- hosts: jdk
  user: root
  ignore_errors: yes
  vars:
    - install_dir: "/usr/local"
    - install_pkg: "jdk-8u241-linux-x64.tar.gz"
    - unavri_name: "jdk1.8.0_241"
  roles:
    - jdk
2.2 定义剧本
[root@elk01 ansible-playbook]# cat jdk/tasks/main.yml
- name: copy-id ssh key
  authorized_key:
      user: root
      key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"
      state: present
      exclusive: no

- name: copy jdk pkg
  unarchive: src={{ install_pkg }} dest=/usr/local copy=yes

- name: add jdk env
  shell: /bin/echo {{  item  }} >> /etc/profile && source /etc/profile
  with_items:
    - export JAVA_HOME={{ install_dir }}/{{ unavri_name }}
    - export PATH=\$JAVA_HOME/bin:\$PATH
2.3 执行剧本
[root@elk01 ansible-playbook]# ansible-playbook -i hosts install-jdk.yml