Gerenciar ambiente Linux com Ansible ad hoc
Módulo user
Adicionando um usuário
$ echo 'senha123' | openssl passwd -1 -stdin
$1$Q0ADxehE$IKy8PGjnj8xryj06jYBa61
$ sudo ansible local -m user -a 'name=helpdesk state=present shell=/bin/bash password=$1$Q0ADxehE$IKy8PGjnj8xryj06jYBa61'
ansible-server | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 1001,
"home": "/home/helpdesk",
"name": "helpdesk",
"password": "NOT_LOGGING_PASSWORD",
"shell": "/bin/bash",
"state": "present",
"system": false,
"uid": 1001
}
Explicação
-m: Determina o nome do módulo, em nosso exemplo será user;
-a: Define argumentos passados ao módulo.
Argumentos
state: Define o estado do usuário como presente (present) e ausente (absent);
shell: Estabelece a shell utilizada pelo novo usuário;
password: Determina o hash de senha do usuário. No exemplo, criamos a hash através do comando openssl passwd -1.
$ getent passwd helpdesk
helpdesk:x:1001:1001::/home/helpdesk:/bin/bash
Para remover o usuário
$ sudo ansible local -m user -a 'name=helpdesk state=absent remove=yes'
ansible-server | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": true,
"force": false,
"name": "helpdesk",
"remove": true,
"state": "absent",
"stderr": "userdel: helpdesk mail spool (/var/mail/helpdesk) not found\n",
"stderr_lines": [
"userdel: helpdesk mail spool (/var/mail/helpdesk) not found"
]
}
Módulo package
Para instalar um pacote
$ sudo ansible local -m package -a 'name=htop state=present'
ansible-server | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"cache_update_time": 1661262472,
"cache_updated": false,
"changed": false
}
Para remover um pacote
$ sudo ansible local -m package -a 'name=htop state=absent'
Módulo file
$ sudo ansible local -m file -a 'path=/etc/nologin owner=root group=root mode=0644 state=touch'
ansible-server | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": true,
"dest": "/etc/nologin",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 0,
"state": "file",
"uid": 0
}
Argumentos
path: Define a localização e nome do arquivo;
owner: Estabelece o usuário dono do arquivo;
group: Indica o grupo dono do arquivo;
mode: Define em forma octal as permissões de acesso ao arquivo.
Para remover
$ ansible local -m file -a 'path=/etc/nologin state=absent'