ansible 批量按用户名创建kerberos主体,并分发到远程主机
可以批量生产票据并分发目标主机
- name: Configure Kerberos for Hadoop Users
hosts: hadoop_servers
become: no
gather_facts: no
vars:
kerberos_server: hadoop01.xuexi.com
keytab_dir: /home/hadoop/hxy
keytab_local_dir: ./keytabs
principals:
- hxy
- stars
tasks:
- name: Ensure key directory exists
ansible.builtin.file:
path: "{
{ keytab_dir }}"
state: directory
mode: '0755'
- name: Create Kerberos principals and generate keytab files
block:
- name: Create a Kerberos principal
ansible.builtin.command: >
kadmin.local -q "addprinc -randkey {
{ item }}/{
{ inventory_hostname }}@XUEXI.COM"
register: addprinc_results
delegate_to: "{
{ kerberos_server }}"
ignore_errors: yes
loop: "{
{ principals }}"
- name: Set facts for successfully created principals
set_fact:
created_principals: "{
{ created_principals | default([]) + [item.item] }}"
when: item.rc == 0
loop: "{
{ addprinc_results.results }}"
- name: Report failed principal creation attempts
ansible.builtin.debug:
msg: "Failed to create principal for {
{ item.item }}/{
{ inventory_hostname }}@XUEXI.ICOM: {
{ item.stderr }}"
when: "'Principal already exists' not in item.stderr and item.rc != 0"
loop: "{
{ addprinc_results.results }}"
- name: Generate keytab file for each principal
ansible.builtin.command: >
kadmin.local -q "xst -k {
{ keytab_dir }}/{
{ item }}-{
{ inventory_hostname }}.keytab -norandkey {
{ item }}/{
{ inventory_hostname }}@XUEXI.COM"
register: xst_results
delegate_to: "{
{ kerberos_server }}"
loop: "{
{ created_principals }}"
- name: Fetch the keytab files to the control machine
ansible.builtin.fetch:
src: "{
{ keytab_dir }}/{
{ item }}-{
{ inventory_hostname }}.keytab"
dest: "{
{ keytab_local_dir }}/{
{ item }}-{
{ inventory_hostname }}.keytab"
flat: yes
delegate_to: "{
{ kerberos_server }}"
when: item is defined and (lookup('file', keytab_dir + '/' + item + '-' + inventory_hostname + '.keytab') is not none)
loop: "{
{ created_principals }}"
- name: Distribute keytab files to each target host
ansible.builtin.copy:
src: "{
{ keytab_local_dir }}/{
{ item }}-{
{ inventory_hostname }}.keytab"
dest: "/data1/tmp/{
{ item }}-{
{ inventory_hostname }}.keytab"
when: item is defined and (lookup('file', keytab_local_dir + '/' + item + '-' + inventory_hostname + '.keytab') is not none)
loop: "{
{ created_principals }}"
delegate_to: "{
{ inventory_hostname }}"
- name: Clean up keytab files on Kerberos server
ansible.builtin.file:
path: "{
{ keytab_dir }}/{
{ item }}-{
{ inventory_hostname }}.keytab"
state: absent
when: item is defined
delegate_to: "{
{ kerberos_server }}"
loop: "{
{ created_principals }}"
- name: Clean up local keytab files on control machine
ansible.builtin.file:
path: "{
{ keytab_local_dir }}/{
{ item }}-{
{ inventory_hostname }}.keytab"
state: absent
when: item is defined
loop: "{
{ created_principals }}"
run_once: yes