Creating a new user and password with Ansible

后端 未结 22 1476
迷失自我
迷失自我 2020-12-22 17:00

I have an ansible task which creates a new user on ubuntu 12.04;

- name: Add deployment user
    action: user name=deployer password=mypassword
22条回答
  •  执念已碎
    2020-12-22 17:26

    I want to propose yet another solution:

    - name: Create madhead user
      user:
        name: madhead
        password: "{{ 'password' | password_hash('sha512') }}"
        shell: /bin/zsh
        update_password: on_create
      register: madhead
    - name: Force madhead to change password
      shell: chage -d 0 madhead
      when: madhead.changed
    

    Why it is better? Like already has been noted here, Ansible plays should be idempotent. You should think of them not as a sequence of actions in imperative style, but like a desired state, declarative style. As a result you should be able to run it multiple times and get the same result, the same server state.

    This all sounds great, but there are some nuances. One of them is managing users. "Desired state" means that every time you run a play that creates a user he will be updated to match exactly that state. By "updated" I mean that his password will be changed too. But most probably it is not what you need. Usually, you need to create user, set and expire his password only once, further play runs shouldn't update his password.

    Fortunately, Ansible has update_password attribute in user module that solves this issue. Mixing this with registered variables you can also expire his password only when the user is actually updated.

    Note that if you change user's shell manually (suppose, you don't like the shell that evil admin forced in his play) the user will be updated, thus his password will be expired.

    Also note how you can easily use plain text initial passwords in plays. No need to encode them somewhere else and paste hashes, you can use Jinja2 filter for that. However, this can be a security flaw if someone happens to login before you initially do.

提交回复
热议问题