变量
Ansible 变量介绍
我们在PlayBook一节中,将PlayBook类比成了Linux中的shell。那么它作为一门Ansible特殊的语言,肯定要涉及到变量定义、控制结构的使用等特性。在这一节中主要讨论变量的定义和使用。
变量命名规则
变量的名字由字母、下划线和数字组成,必须以字母开头。
如下变量命名为正确:
good_a OK
ok_b OK
如下变量命名为错误:
_aaa FAIL
2_bb FAIL
保留关键字不能作为变量名称
add, append, as_integer_ratio, bit_length, capitalize, center, clear,
conjugate, copy, count, decode, denominator, difference,
difference_update, discard, encode, endswith, expandtabs,
extend, find, format, fromhex, fromkeys, get, has_key, hex,
imag, index, insert, intersection, intersection_update, isalnum,
isalpha, isdecimal, isdigit, isdisjoint, is_integer, islower,
isnumeric, isspace, issubset, issuperset, istitle, isupper,
items, iteritems, iterkeys, itervalues, join, keys, ljust, lower,
lstrip, numerator, partition, pop, popitem, real, remove,
replace, reverse, rfind, rindex, rjust, rpartition, rsplit, rstrip,
setdefault, sort, split, splitlines, startswith, strip, swapcase,
symmetric_difference, symmetric_difference_update, title,
translate, union, update, upper, values, viewitems, viewkeys,
viewvalues, zfill
变量类型
根据变量的作用范围大体的将变量分为:
- 全局变量
- 剧本变量
- 主机变量。
但只是一个比较粗糙的划分,不能囊括Ansible 中的所有变量。下面将分别从这三种变量入手,去介绍变量的使用
实验步骤:
1 首先对被控制节点 192.168.116.145
进行修改配置文件,使 sshd 服务监督 2222 端口,并添加用户 shark.
2 在控制节点(ansible 机器)上操作,和 192.168.116.145 机器的 shark 用户建立密钥信任关系。
ssh-copy-id [email protected] -p2222 (-p 指定端口)
3 编译控制节点的资产清单文件 hosts ,添加ssh链接时使用的端口和用户
[root@ansible-server ~]# cat hosts
[dbservers]
192.168.122.106 ansible_ssh_port=2222 ansible_ssh_user=shark
192.168.122.218
4 执行任务,验证
[root@ansible-server ~]# ansible dbservers -i hosts -m shell -a "hostname;id"
192.168.122.218 | CHANGED | rc=0 >>
ela3
uid=0(root) gid=0(root) 组=0(root)
192.168.122.106 | CHANGED | rc=0 >>
ela2
uid=1000(shark) gid=1001(shark) 组=1001(shark),1000(db_admin),1002(web_admin)
---
- name: 测试使用非 22 端口和非 root 用户连接被控节点
hosts: dbservers
gather_facts: no
#开启提取
ecome: yes
#成为哪个用户, 默认是 root
#become_user: test
#提取方法,默认 sudo
#become_method: su
tasks:
- name: 执行 shell 命令,返回主机名和远程用户的 id 信息
shell: hostname;id;ls /root
register: mss
- name: debug
debug:
msg: "{
{mss}}"
...
[root@localhost ~]# cat facts.yml
---
- name: print facts variable
hosts: dbservers
#关闭 Facts 信息的收集,
#gather_facts: no
tasks:
- name: print facts variable
debug:
msg: "The data is{
{ ansible_apparmor.status }} {
{ansible_date_time.year }} "
...
[root@localhost ~]# ansible-playbook -i hosts facts.yml
提权
1 remote_user 指定的用户需要是 sudo
---
- name: 提权
hosts: dbservers
remote_user: shark
gather_facts: no
# 开启提取
become: yes
tasks:
- name: 执行 shell 命令,返回主机名和远程用户的 id 信息
shell: hostname;id;ls /root
register: mss
- name: debug
debug:
msg: "{
{mss}}"
...
2 执行时候:
需要提供 remote_user 指定的用户(shark)的密码
提供密码两种方式
-
方式一: 使用 -K ,之后输入密码
ansible-playbook -i hosts become-user.yml -K
-
方式二: 设置主机变量 ansible_become_password=shark用户的密码
ansible-playbook -i hosts become-user.yml