Ansible定义命令行、主机/主机组、playbook等变量,注册变量和vars_prompt的用法示例

目录

一.Ansible定义变量

1.用途

2.定义规则

3.变量优先级

二.命令行定义变量

三.定义主机和主机组变量

1.主机变量

(1)内置主机变量

(2)简单示例

2.主机组变量

四.定义playbook变量

1.通过vars表示定义变量,通过' "{{变量名}}" '来引用变量

2.通过vars_file指定变量文件

五.定义host_vars和group_vars目录变量

1.主机组变量使用group_vars

2.主机变量只用host_vars

3.以主机变量简单为例演示

六.注册变量

七.vars_prompt交互变量

1.参数解析

2.简单交互案例

3.创建用户和密码示例

(1)encrypt

(2)confirm


 

一.Ansible定义变量

1.用途

ansible的变量主要用于存储在整个项目中重复使用的一些值,来提高创建任务和维护节点的效率

2.定义规则

变量名由字母、数字、下划线组成,由字母开头

内置关键字不能作为变量名

3.变量优先级

全局范围内命令行设置的变量>playbook及其相关配置的变量>主机和组清单的变量>ansible.cfg配置文件设置的变量

二.命令行定义变量

如上文所述,命令行使用"-e '变量名=值' "设置的变量优先级最高,下面举例演示命令行变量覆盖playbook中的变量

[root@main ~]# cat abc.yaml 
---
- hosts: webservers
  vars:
    myservice: httpd   #原本playbook内容为停掉httpd
  tasks:
    - name: test1
      service:
        name: "{{ myservice }}"
        state: stopped
[root@main ~]# ansible-playbook abc.yaml -e 'myservice=chronyd'
#运行时指定变量更改为关掉chronyd
[root@main ~]# ansible webservers -m shell -a 'systemctl status httpd | grep Active'
serverb | CHANGED | rc=0 >>
   Active: active (running) since Tue 2023-10-17 14:06:57 CST; 5h 22min ago
servera | CHANGED | rc=0 >>
   Active: active (running) since Tue 2023-10-17 19:25:46 CST; 3min 12s ago
[root@main ~]# ansible webservers -m shell -a 'systemctl status chronyd | grep Active'
serverb | CHANGED | rc=0 >>
   Active: inactive (dead) since Tue 2023-10-17 19:28:30 CST; 35s ago
servera | CHANGED | rc=0 >>
   Active: inactive (dead) since Tue 2023-10-17 19:28:30 CST; 35s ago
#运行结果可以看出,停掉httpd未生效,停chonyd生效,命令行给定变量优先级高于playbook给定变量优先级

三.定义主机和主机组变量

1.主机变量

(1)内置主机变量

在变量前加上"ansible_"即成为内置变量

部分内置主机关于ssh和提权的变量举例

ansible_ssh_host:指定受管节点主机真实IP地址
ansible_ssh_port:指定通过哪个端口连接受管节点
ansible_ssh_user:指定连接时使用的用户名称
ansibe_connection:指定ssh连接类型,local、ssh、paramiko
ansible_ssh_pass:ssh连接时使用的密码
ansible_ssh_executable:指定ssh指定的路径
​
ansible_become:允许特权升级,等同于ansible_sudo,ansible_su
ansible_become_user:提权到哪个用户,等同于ansible_sudo_user,ansible_su_user
ansbile_become_pass:需要密码时指定密码,等同于ansible_sudo_pass
ansible_sudo_exec:指定sudo命令路径

(2)简单示例

[student@workstation ~]$ vim user.yml
#不属于任何组的用户
192.168.2.190 ansible_ssh_user=root ansible_user_pass='redhat'
192.168.2.191 ansible_ssh_user=root ansible_user_pass='su123'

2.主机组变量

如上例,将两台受管节点相等的部分定义为一个变量

[student@workstation ~]$ vim user.yml
192.168.2.190 ansible_ssh_user=root ansible_user_pass='redhat'
192.168.2.191 ansible_ssh_user=root ansible_user_pass='su123'
#更改为
192.168.2.190  ansible_user_pass='redhat'
192.168.2.191  ansible_user_pass='su123'
[webservers:vars]
ansible_ssh_user=root

四.定义playbook变量

1.通过vars表示定义变量,通过' "{{变量名}}" '来引用变量

[root@localhost ~]# cat httpd.yaml 
---
- name: install httpd chrony
  hosts: webservers
  vars:   #声明在此处定义变量
    mypackages:     #变量名
      - httpd
      - chrony
    myhttpd: httpd 
    mychronyd: chronyd
  tasks:
    - name: install them
      yum:
        name: "{{ mypackages }}"   #使用变量
        state: present
    - name: start httpd
      service:
        name: "{{ myhttpd }}"
        state: started
    - name: start chronyd
      service:
        name: "{{ mychronyd }}"
        state: started
​
[root@localhost ~]# ansible webservers -m shell -a 'systemctl status httpd | grep Active'
serverb | CHANGED | rc=0 >>
   Active: active (running) since Tue 2023-10-17 14:06:57 CST; 3min 45s ago
servera | CHANGED | rc=0 >>
   Active: active (running) since Tue 2023-10-17 14:06:57 CST; 3min 45s ago
[root@localhost ~]# ansible webservers -m shell -a 'systemctl status chronyd | grep Active'
servera | CHANGED | rc=0 >>
   Active: active (running) since Tue 2023-10-17 13:29:27 CST; 41min ago
serverb | CHANGED | rc=0 >>
   Active: active (running) since Tue 2023-10-17 13:31:57 CST; 38min ago

2.通过vars_file指定变量文件

[root@main ~]# cat myvar1.yaml   #vars文件也使用yaml格式
packages:
  - rpcbind
  - openssl
  
[root@main ~]# cat httpd1.yaml 
---
- name: install rpcbind openssl
  hosts: webservers
  tasks:
    - name: install them
      yum:
        name: "{{ packages }}"   #同样这样使用变量
        state: present
  vars_files:   #指定vars文件
    - myvar1.yaml   #指定你自己的vars问文件位置,这里是当前路径下的myvars1.yaml文件
​
[root@main ~]# ansible-playbook httpd1.yaml --syntax-check
​
playbook: httpd1.yaml
[root@main ~]# ansible-playbook httpd1.yaml 
​
[root@main ~]# ansible webservers -m shell -a 'yum list installed | grep rpcbind'
servera | CHANGED | rc=0 >>
rpcbind.x86_64                        0.2.0-49.el7                     @base    
serverb | CHANGED | rc=0 >>
rpcbind.x86_64                        0.2.0-49.el7                     @base    
[root@main ~]# ansible webservers -m shell -a 'yum list installed | grep openssl'
servera | CHANGED | rc=0 >>
openssl.x86_64                        1:1.0.2k-19.el7                  @anaconda
openssl-libs.x86_64                   1:1.0.2k-19.el7                  @anaconda
xmlsec1-openssl.x86_64                1.2.20-7.el7_4                   @anaconda
serverb | CHANGED | rc=0 >>
openssl.x86_64                        1:1.0.2k-19.el7                  @anaconda
openssl-libs.x86_64                   1:1.0.2k-19.el7                  @anaconda
xmlsec1-openssl.x86_64                1.2.20-7.el7_4                   @anaconda

五.定义host_vars和group_vars目录变量

1.主机组变量使用group_vars

group_vars是一个目录,这个名称固定,必须是和你的inventory文件和ansible.cfg文件位于同一级目录,其下创建的文件需要和你主机清单中的组名称一致,在这个文件中写入变量和值

2.主机变量只用host_vars

host_vars和group_vars相同,也是一个目录,名称固定,必须和inventory文件和ansible.cfg文件位于同一级目录,其下创建的文件需要和你主机清单中的主机名称一致(清单文件中写的是主机名就写=用主机名,是IP地址就用IP地址),在这个文件中写入变量和值

3.以主机变量简单为例演示

[root@main ~]# tree /root
/root
├── anaconda-ks.cfg
├── ansible.cfg
├── group_vars
│   ├── dbservers
│   └── webservers
├── host_vars
│   ├── servera
│   └── serverb
├── httpd1.yaml
├── httpd.yaml
├── myhosts
├── myhttpd.yaml
└── myvar1.yaml
​
[root@main ~]# cat host_vars/servera
aname: httpd
[root@main ~]# cat host_vars/serverb
bname: mod_ssl
​
[root@main ~]# cat myhttpd.yaml 
---
- name: stop servera httpd
  hosts: servera
  tasks:
    - name: stop it
      service:
        name: "{{ aname }}"     #在剧本中就可以直接用用定义好的主机变量
        state: stopped
- name: install serverb mod_ssl
  hosts: serverb
  tasks:
    - name: install it
      yum:
        name: "{{ bname }}"
        state: present
​
[root@main ~]# ansible-playbook myhttpd.yaml --syntax-check
​
playbook: myhttpd.yaml
[root@main ~]# ansible-playbook myhttpd.yaml
​
[root@main ~]# ansible servera -m shell -a 'systemctl status httpd | grep Active'
servera | CHANGED | rc=0 >>
   Active: inactive (dead)
[root@main ~]# ansible serverb -m shell -a 'yum list installed | grep mod_ssl'
serverb | CHANGED | rc=0 >>
mod_ssl.x86_64                        1:2.4.6-99.el7.centos.1          @updates 

六.注册变量

注册变量主要是使用register来捕获命令的输出,将其保存在一个临时变量中,便于进行特定操作。

如下例,将"id su"的结果注册为"su",并使用debug模块输出su的内容,并在playbook执行后的debug结果中判断出该用户是否存在

[root@main ~]# cat iduser.yaml 
---
- name: is su exist
  hosts: webservers
  tasks:
    - name: test su
      shell: id su
      register: su
      ignore_errors: yes   #便于测试,忽略错误
    - name: echo it
      debug:
        msg: "{{ su }}"
​
[root@main ~]# ansible-playbook iduser.yaml
​
PLAY [is su exist] ******************************************************************************************************************************
​
TASK [Gathering Facts] **************************************************************************************************************************
ok: [servera]
ok: [serverb]
​
TASK [test su] **********************************************************************************************************************************
changed: [servera]
changed: [serverb]
​
TASK [echo it] **********************************************************************************************************************************
ok: [servera] => {
    "msg": {
        "changed": true, 
        "cmd": "id su", 
        "delta": "0:00:00.004109", 
        "end": "2023-10-17 19:05:47.215481", 
        "failed": false, 
        "rc": 0,   #为0表示存在,非0不存在
        "start": "2023-10-17 19:05:47.211372", 
        "stderr": "", 
        "stderr_lines": [], 
        "stdout": "uid=1000(su) gid=1000(su) groups=1000(su)",    #有会输出该用户的详细信息,没有会提示不存在此用户
        "stdout_lines": [
            "uid=1000(su) gid=1000(su) groups=1000(su)"
        ]
    }
}
ok: [serverb] => {
    "msg": {
        "changed": true, 
        "cmd": "id su", 
        "delta": "0:00:00.004695", 
        "end": "2023-10-17 19:05:47.220915", 
        "failed": false, 
        "rc": 0, 
        "start": "2023-10-17 19:05:47.216220", 
        "stderr": "", 
        "stderr_lines": [], 
        "stdout": "uid=1000(su) gid=1000(su) groups=1000(su)", 
        "stdout_lines": [
            "uid=1000(su) gid=1000(su) groups=1000(su)"
        ]
    }
}
​
PLAY RECAP **************************************************************************************************************************************
servera                    : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
serverb                    : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

七.vars_prompt交互变量

用于交互提示用户输入值

1.参数解析

prompt表示对用户的提示信息

private表示用户在输入时是否隐藏输入的信息

default表示如果用户没有输入,则此项的默认值

2.简单交互案例

[root@main ~]# cat register.yaml 
---
- hosts: webservers
  vars_prompt:
    - name: "one"
      prompt: "请输入第一个值"
      private: no
    - name: "two"
      prompt: "请输入第二个值"
      #default: 'hello'
      private: yes
  tasks:
    - name: dis one value
      debug: msg="{{one}}"
    - name: dis two value
      debug: msg="{{two}}"
#测试结果
[root@main ~]# ansible-playbook register.yaml
请输入第一个值: nihao
请输入第二个值:             #private为yes,此处我输入时会隐藏信息
​
PLAY [webservers] *******************************************************************************************************************************
​
TASK [Gathering Facts] **************************************************************************************************************************
ok: [servera]
ok: [serverb]
​
TASK [dis one value] ****************************************************************************************************************************
ok: [servera] => {
    "msg": "nihao"
}
ok: [serverb] => {
    "msg": "nihao"
}
​
TASK [dis two value] ****************************************************************************************************************************
ok: [servera] => {        #显示输入的信息
    "msg": "hello"
}
ok: [serverb] => {
    "msg": "hello"
}
​
PLAY RECAP **************************************************************************************************************************************
servera                    : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
serverb                    : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

3.创建用户和密码示例

(1)encrypt

可以指定在密码处可以指定使用sha512对密码进行哈希加密

(2)confirm

可以设置重复确认密码,两次密码不符合会报“* VALUES ENTERED DO NOT MATCH ”

[root@main ~]# cat register1.yaml 
---
- hosts: webservers
  vars_prompt:
    - name: "name"
      prompt: "enter user_name"
      private: no
    - name: "passwd"
      prompt: "enter user_passwd"
      private: yes
      #encrypt: "sha512_crypt"   
      #confirm: yes           
  tasks:
    - name: create him
      user:
        name: "{{ name }}"
        password: "{{ passwd }}"
​
[root@main ~]# ansible-playbook register1.yaml
enter user_name: sulibao
enter user_passwd: 
[WARNING]: Found variable using reserved name: name
​
PLAY [webservers] *******************************************************************************************************************************
​
TASK [Gathering Facts] **************************************************************************************************************************
ok: [serverb]
ok: [servera]
​
TASK [create him] *******************************************************************************************************************************
[WARNING]: The input password appears not to have been hashed. The 'password' argument must be encrypted for this module to work properly.
changed: [serverb]
changed: [servera]
​
PLAY RECAP **************************************************************************************************************************************
servera                    : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
serverb                    : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
​
[root@main ~]# ansible webservers -a 'id sulibao'
serverb | CHANGED | rc=0 >>
uid=1001(sulibao) gid=1001(sulibao) groups=1001(sulibao)
servera | CHANGED | rc=0 >>
uid=1001(sulibao) gid=1001(sulibao) groups=1001(sulibao)
​
#未加密的密码
[root@main ~]# ansible webservers -m shell -a 'cat /etc/shadow | grep sulibao'
serverb | CHANGED | rc=0 >>
sulibao:ansible:19647:0:99999:7:::
servera | CHANGED | rc=0 >>
sulibao:ansible:19647:0:99999:7:::
#加密后
[root@main ~]# ansible webservers -m shell -a 'cat /etc/shadow | grep li'
serverb | CHANGED | rc=0 >>
sulibao:ansible:19647:0:99999:7:::
li:$6$U0qiY4DnzK8AWcBe$rIFmtpCr.1qU3sxtv90U2bRaZbxgqj1PK9UV4wp6W8zWXigHTfcfuFjJ0AvCZMb0Xe75juLlarm94xNZUnoCX.:19647:0:99999:7:::
servera | CHANGED | rc=0 >>
sulibao:ansible:19647:0:99999:7:::
li:$6$U0qiY4DnzK8AWcBe$rIFmtpCr.1qU3sxtv90U2bRaZbxgqj1PK9UV4wp6W8zWXigHTfcfuFjJ0AvCZMb0Xe75juLlarm94xNZUnoCX.:19647:0:99999:7:::

 

你可能感兴趣的:(Linux,#,ansible,linux,ansible,运维,ansible变量,vars_prompt)