使用Ansible Playbook自动更改用户密码

时间:2019-07-01 17:13:34

标签: ansible

我想更改用户密码(如果存在),但是出现此错误

这里是我的代码

     - name: Check for foo user
       with_items: foo
       changed_when: false
       command: grep {{ item }} -q /etc/passwd
       register: find_user


     - name: Update foo user's Password
       user:
         name: foo
         update_password: always
         password: $6$rounds=656000$ZjMwlMPWqwGKF1nY$JbarjwHGtlr5PD3Yqfb5phz18gnHujSgmpD29DxsXQ7a7UdhuO
       when: find_user is changed


TASK [Check for foo user] *****************************************************************************************************************************************************************************************
fatal: [192.168.56.124]: FAILED! => {"changed": false, "cmd": "grep -w 'foo' /etc/passwd", "delta": "0:00:00.003024", "end": "2019-07-01 12:59:45.966160", "msg": "non-zero return code", "rc": 1, "start": "2019-07-01 12:59:45.963136", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}

2 个答案:

答案 0 :(得分:0)

那是因为当/ etc / passwd文件中不存在用户名时,您拥有的command任务的退出代码= 1:

[http_offline@greenhat-29 tests]$ grep foo -q /etc/passwd
[http_offline@greenhat-29 tests]$ echo $?
1
[http_offline@greenhat-29 tests]$ grep root -q /etc/passwd     
[http_offline@greenhat-29 tests]$ echo $?
0
[http_offline@greenhat-29 tests]$ 

您可以做的是,指示grep命令的退出代码不是0或1时,此任务不会失败。为此,您需要在命令任务中添加此子句:

failed_when: find_user.rc !=0 and find_user.rc !=1

整个任务如下:

  - name: Check for foo user
    with_items: foo
    changed_when: false
    command: grep {{ item }} -q /etc/passwd
    register: find_user
    failed_when: find_user.rc !=0 and  find_user.rc !=1

希望这会有所帮助。

答案 1 :(得分:0)

使用getent模块来测试用户的存在。

- name: Read passwd
  getent:
    database: passwd

- name: Update foo users password
  user:
    name: foo
    update_password: always
    password: ...
  when: "'foo' in getent_passwd"