# Ansible Cheatsheet

### Ping machine

```bash
ansible -i ./inventory/hosts <group_name> -m <command> --user <server_user> --ask-pass
```

### Password prompt with apk-pass

{% hint style="warning" %}
Note that this is not safe, usually better to use SSH Keys
{% endhint %}

```bash
ansible -i ~/ansible/inventory servers -m ping --user root --ask-pass
```

## Playbook run:

{% hint style="info" %}
playbooks are used to automate tasks
{% endhint %}

###

### To run playbook:

```bash
ansible-playbook ~/ansible/playbooks/<playbook_name> --user <server_user> --ask-pass --ask-become-pass -i ~/ansible/inventory
```

{% hint style="info" %}
\--ask-become-pass asks to become super user
{% endhint %}

###

### To run playbook and become super user:

```bash
ansible-playbook ./playbooks/apt.yml --user root --ask-become-pass -i ./inventory/hosts
```

###

### To run playbook with specific key use args: --key-file

```bash
ansible-playbook $HOME/playbooks/apt.yml --user root --ask-become-pass -i $HOME/inventory/hosts --key-file $HOME/.ssh/ansible_ed25519
```

###

### To run playbook for ssh autorized\_keys:

```bash
ansible-playbook $HOME/playbooks/autorized_keys.yml --user root --ask-become-pass -i $HOME/inventory/hosts --key-file $HOME/.ssh/ansible_ed25519
```

###

### To check playbook syntax use:

```bash
ansible-playbook foo.yml --check
```

### To check the playbook tags use:

{% hint style="info" %}
ansible-playbook \<path-to-playbook/playbook.yml> --list-tags
{% endhint %}

```bash
ansible-playbook $HOME/playbooks/user_management.yml --list-tags
```

###

### To execute playbook with tags use:

```bash
ansible-playbook <path_to_playbook/paybook.yml> --tags <tag_name>
ansible-playbook $HOME/playbooks/user_management.yml --tags add_new_group
```

###

### To execute multiple tags:

```bash
ansible-playbook $HOME/playbooks/user_management.yml --tags add_new_group,add_new_user
```

###

### To execute playbook for specific groups, you have to provide the hosts file like so:

```bash
ansible-playbook -i inventory/hosts playbooks/user_management.yml --tags 
add_new_group
```

###

### The playbook must include the group required to run this:

```bash
- hosts: other
  become_user: root
```

###

### To roll out specific hosts file with specific user and user password run:

```bash
ansible-playbook -i $HOME/inventory/hosts $HOME/playbooks/initial_server_config.yml --tags create_users,create_groups,add_users_to_sudo --user root --ask-pass
```
