四、Ansible Register
1、什么是Register
register 可以将 task 执行的任务结果存储至某个变 量中,便于后续的引用;
例1获取被控节点的端口信息
cat f5.yml
---
- hosts: all
tasks:
- name:
shell: netstat -lntp
register: System_Status
- name: Get System Status
debug: msg={{System_Status.stdout_lines}}
例2批量修改主机名称
cat te_2.yaml
- hosts: all
tasks:
- name: #定义一个随机数,设定为变量,然后后续调用
shell: echo $((RANDOM%200))
register: System_SJ
- name: #使用debug输出变量结果,这样好知道需要提取的关键值
debug: msg={{ System_SJ }}
- name: #使用hostname模块将主机名修改为web_随机数
hostname: name=web_{{System_SJ.stdout }}
例3jumpserver key 的创建
if [ ! "$BOOTSTRAP_TOKEN" ]; then
BOOTSTRAP_TOKEN=`cat /dev/urandom | tr -dc A-Za-z0-9 | head -c 16`;
echo "BOOTSTRAP_TOKEN=$BOOTSTRAP_TOKEN"
>> ~/.bashrc;
echo $BOOTSTRAP_TOKEN;
else
echo $BOOTSTRAP_TOKEN;
fi
cat f9.yaml
- hosts: webservers
tasks:
- name: Run Shell Command Random string
shell:
cmd: 'if ! grep "SECRET_KEY" ~/.bashrc; then
SECRET_KEY=`cat /dev/urandom | tr -dc A-Za-z0-9 | head -c 50`;
echo "SECRET_KEY=$SECRET_KEY" >> ~/.bashrc;
echo $SECRET_KEY;
else
echo $SECRET_KEY;
fi'
register: SECRET_KEY
- name: Run Shell CommandBOOTSTRAP_TOKEN
shell:
cmd: 'if ! grep "BOOTSTRAP_TOKEN" ~/.bashrc; then
BOOTSTRAP_TOKEN=`cat /dev/urandom | tr -dc A-Za-z0-9 | head -c 16`;
echo "BOOTSTRAP_TOKEN=$BOOTSTRAP_TOKEN" >> ~/.bashrc;
echo $BOOTSTRAP_TOKEN;
else
echo $BOOTSTRAP_TOKEN;
fi'
register: BOOTSTRAP_TOKEN
- name: Copy Jms Configure
template:
src: ./j-config.yml
dest: /tmp/jms_config.yml
- name: Copy Koko Configure
template:
src: ./k-config.yml
dest: /tmp/koko_config.yml
# 配置文件中:
SECRET_KEY: {{ SECRET_KEY.stdout.split('=')[1] }}
BOOTSTRAP_TOKEN: {{ BOOTSTRAP_TOKEN.stdout.split('=')[1] }}