Create password and write it to file - ansible

The idea is to generate user accounts over an API. Using default variables as the basic information:
---
students:
- Username: testuser1
E-Mail: student1#student.com
- Username: testuser2
E-Mail: student2#student.com
The Creating User role will then create all users with the API:
- name: "Creating User"
uri:
url: "https://URL/api/v1/users"
method: POST
headers:
Content-Type: application/json
Authorization: AUTH TOKEN
body:
name: "{{ item['Username'] }}"
email: "{{ item['E-Mail'] }}"
password: "{{ item['Password'] }}"
body_format: json
validate_certs: no
loop: "{{ students }}"
I can not find a way to generate a password for each user and write them to a file. Is there a way I can append a Password variable to each student item before the Creating User role? If so I could just write the default variable to a file as a last role.
I've played with the password module. I do not want to have 100+ files with the passwords of the users. I need to have a singe file at the end with all information.

I'm not 100% sure I understood your question.
The below will take your actual user list, create a new one with a generated password for each and store the result in a single file for all users. Bonus: if the file exists, the var will be initialized from there bypassing the password creation.
Notes:
The below can be enhanced. You can put the block tasks for file creation in a separate file and use a conditional include so that the skipped loop iteration do not take place at all when the file already exists.
I obviously did not take security into account here and I strongly suggest you secure the way your file is stored.
Demo playbook:
---
- name: Create random passwords and store
hosts: localhost
gather_facts: false
vars:
users_with_pass_file: /tmp/test_pass.txt
students:
- Username: testuser1
E-Mail: student1#student.com
- Username: testuser2
E-Mail: student2#student.com
tasks:
- name: Try to load users and passwords from file if it exists
vars:
file_content: "{{ lookup('ansible.builtin.file', users_with_pass_file, errors='ignore') }}"
ansible.builtin.set_fact:
users_with_pass: "{{ file_content }}"
when:
- file_content | length > 0
# Unfortunately, there is no test 'is list' in jinja2...
- file_content is iterable
- file_content is not mapping
- file_content is not string
ignore_errors: true
changed_when: false
register: load_from_disk
- name: Create user list with passwords and store it if it does not exists (or is malformed...)
block:
- name: Create the list
vars:
user_password: "{{ lookup('ansible.builtin.password', '/dev/null', length=12) }}"
ansible.builtin.set_fact:
users_with_pass: "{{ users_with_pass | default([]) + [item | combine({'password': user_password})] }}"
loop: "{{ students }}"
- name: Store the result
ansible.builtin.copy:
dest: "{{ users_with_pass_file }}"
content: "{{ users_with_pass | to_json }}"
when: load_from_disk is skipped or load_from_disk is failed
- name: Show the result
ansible.builtin.debug:
var: users_with_pass
first run (with used ansible version):
$ ansible-playbook --version
ansible-playbook 2.10.1
config file = None
configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.6/dist-packages/ansible
executable location = /usr/local/bin/ansible-playbook
python version = 3.6.9 (default, Jul 17 2020, 12:50:27) [GCC 8.4.0]
$ ansible-playbook test.yml
PLAY [Create random passwords and store] ***********************************************************************************************************************************************************************************************
TASK [Try to load users and passwords from file if it exists] **************************************************************************************************************************************************************************
[WARNING]: Unable to find '/tmp/test_pass.txt' in expected paths (use -vvvvv to see paths)
skipping: [localhost]
TASK [Create the list] *****************************************************************************************************************************************************************************************************************
ok: [localhost] => (item={'Username': 'testuser1', 'E-Mail': 'student1#student.com'})
ok: [localhost] => (item={'Username': 'testuser2', 'E-Mail': 'student2#student.com'})
TASK [Store the result] ****************************************************************************************************************************************************************************************************************
changed: [localhost]
TASK [Show the result] *****************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"users_with_pass": [
{
"E-Mail": "student1#student.com",
"Username": "testuser1",
"password": "5l1RG7HzqaKMWJcH:mRH"
},
{
"E-Mail": "student2#student.com",
"Username": "testuser2",
"password": "tZvLT3LVj3_60GV_WoQd"
}
]
}
PLAY RECAP *****************************************************************************************************************************************************************************************************************************
localhost : ok=3 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
Second run:
PLAY [Create random passwords and store] ***********************************************************************************************************************************************************************************************
TASK [Try to load users and passwords from file if it exists] **************************************************************************************************************************************************************************
ok: [localhost]
TASK [Create the list] *****************************************************************************************************************************************************************************************************************
skipping: [localhost] => (item={'Username': 'testuser1', 'E-Mail': 'student1#student.com'})
skipping: [localhost] => (item={'Username': 'testuser2', 'E-Mail': 'student2#student.com'})
TASK [Store the result] ****************************************************************************************************************************************************************************************************************
skipping: [localhost]
TASK [Show the result] *****************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"users_with_pass": [
{
"E-Mail": "student1#student.com",
"Username": "testuser1",
"password": "5l1RG7HzqaKMWJcH:mRH"
},
{
"E-Mail": "student2#student.com",
"Username": "testuser2",
"password": "tZvLT3LVj3_60GV_WoQd"
}
]
}
PLAY RECAP *****************************************************************************************************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=2 rescued=0 ignored=0

If you have diceware installed, then you can generate the password:
- name: generate new password
delegate_to: localhost
command: diceware --no-caps -d ' ' -w en_eff
register: generatedpass
Then you can store in the file:
- name: store password
copy:
dest: '/path/to/password/file'
content: |
{{ generatedpass }}
If I understand your question correctly, this should do the trick.

Related

Ansible loop giving warning found a duplicate dict key (when). Using last defined value only

I am trying to iterate over an array and assign the value to variables hooks_enabled, workflow_artifact_id, workflow_version, one by one in every iteration and perform a specific task (currently debug, later change to Helm install command).
Code:
---
- name: Executing Ansible Playbook
hosts: localhost
become: yes
become_user: someuser
pre_tasks:
- include_vars: global_vars.yaml
- name: Print some debug information
set_fact:
all_vars: |
Content of vars
--------------------------------
{{ vars | to_nice_json }}
tasks:
- name: Iterate over an array
set_fact:
hooks_enabled: '{{ array_item1_hooks_enabled }}'
workflow_artifact_id: '{{ array_item1_workflow_artifact_id }}'
workflow_version: '{{ array_item1_workflow_version }}'
when: "item == 'array_item1'"
set_fact:
hooks_enabled: '{{ array_item2_hooks_enabled }}'
workflow_artifact_id: '{{ array_item2_workflow_artifact_id }}'
workflow_version: '{{ array_item2_workflow_version }}'
when: "item == 'array_item2'"
with_items: "{{ array}}"
# Change debug with helm install command
- debug:
msg: " id= '{{ workflow_artifact_id }}'"
The issue I am facing is, only the last when is considered and others are skipped
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
[WARNING]: While constructing a mapping from /c/ansible-test/second.yaml, line 16, column 7, found a duplicate dict key (set_fact). Using last defined value only.
[WARNING]: While constructing a mapping from /c/ansible-test/second.yaml, line 16, column 7, found a duplicate dict key (when). Using last defined value only.
PLAY [Executing Ansible Playbook] *********************************************************************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************************************************************************************
ok: [localhost]
TASK [include_vars] ***********************************************************************************************************************************************************************************************
ok: [localhost]
TASK [Print some debug information] *******************************************************************************************************************************************************************************
ok: [localhost]
TASK [Iterate over an array] **************************************************************************************************************************************************************************************
skipping: [localhost] => (item=array_item1)
ok: [localhost] => (item=array_item2)
skipping: [localhost] => (item=array_item3)
skipping: [localhost] => (item=array_item4)
skipping: [localhost] => (item=array_item5)
TASK [debug] ******************************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": " id= 'algorithm-Workflow'"
}
PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
How do I modify the block to enable all the when statement execute and later use helm install command to take the variables one by one.
I would go with a dynamic variable construction using the vars lookup.
Something along the lines of:
- set_fact:
hooks_enabled: "{{ lookup('vars', item ~ '_hooks_enabled') }}"
workflow_artifact_id: "{{ lookup('vars', item ~ '_workflow_artifact_id') }}"
workflow_version: "{{ lookup('vars', item ~ '_workflow_version') }}"
when: "item in ['array_item1', 'array_item2']"
with_items: "{{ array }}"

How to create a specific user on a specific host

There are several computers on the network, on each of them you need to create a user with a specific login and password.
I create users like this:
vars_prompt:
- name: "user_name"
prompt: "User name"
private: no
- name: "user_password"
prompt: "Enter a password for the user"
private: yes
encrypt: "md5_crypt"
confirm: yes
salt_size: 7
tasks:
- name: "add new user"
user:
name: "{{user_name}}"
password: "{{user_password}}"
shell: /bin/bash
Since there are many computers I don’t want to run a playbook a huge number of times. Ideally, I would like to implement the input of the list of hosts (computers) and the list of users. Password, in principle, you can do the same everywhere.
Loop the task
tasks:
- name: "add new user"
user:
name: "{{ item.user_name }}"
password: "{{ item.user_password }}"
shell: /bin/bash
loop: "{{ my_users }}"
and put the variable(s) my_users to host_vars
my_users:
- user_name: user1
user_password: password1
- user_name: user2
user_password: password2
Put common users to group_vars.
See Variable precedence: Where should I put a variable?
Use Ansible Vault to encrypt the passwords.
Here is an example of what you can try. Adapt to your needs.
Note: if the list of users is different for each host, just execute the playbook several times. Implementing this as a promptable play in ansible will just be a total pain and merely unusable.
In the example below, test1 and test2 are pointing to 2 docker containers I added in my demo_inventory.yml.
all:
hosts:
test1:
ansible_connection: docker
test2:
ansible_connection: docker
The hosts you enter will need to be correctly known by ansible for this to work.
This is the demo playbook test.yml
---
- name: Gather needed information
hosts: localhost
vars_prompt:
- name: hosts_entry
prompt: Enter comma separated list of hosts to target
private: false
- name: users_entry
prompt: Enter comma separated list of users to create
private: false
- name: user_password
prompt: Enter initial password applied to all users
encrypt: md5_crypt
confirm: true
salt_size: 7
tasks:
- name: Create a dynamic whatever_group with entered hosts
add_host:
name: "{{ item | trim }}"
groups:
- whatever_group
loop: "{{ hosts_entry.split(',') }}"
- name: Create a list of host for later reuse. Will be scoped to localhost
set_fact:
users_list: "{{ users_entry.split(',') }}"
- name: Store password for later reuse as vars_prompt are limited to play
set_fact:
user_password: "{{ user_password }}"
- name: Do the actual work
hosts: whatever_group
tasks:
- name: Make sure users are present
user:
name: "{{ item | trim }}"
password: "{{ hostvars['localhost'].user_password }}"
shell: /bin/bash
loop: "{{ hostvars['localhost'].users_list }}"
I created a play on localhost to gather the info from vars_prompt. In this play, I used add_host to create a whatever_group dynamically. Note the use of split to create list from a string with comma seperated elements in the input and of trim to remove the leading/trailing spaces (if user entered them). Since vars_prompt are limited in scope to the current play, I also used set_fact to get the users list and the password for future use.
On the next play, I target the whatever_group and run the user task. Note that since set_fact used previously scoped the variables to localhost, we have to use the hostvars magic variable to get the relevant information for the user loop and the password.
Here is the example run
$ ansible-playbook -i demo_inventory.yml test.yml
Enter comma separated list of hosts to target: test1, test2
Enter comma separated list of users to create: user1, user2, user3
Enter initial password applied to all users:
confirm Enter initial password applied to all users:
PLAY [Gather needed information] ***************************************************************
TASK [Gathering Facts] *************************************************************************
ok: [localhost]
TASK [Create a dynamic whatever_group with entered hosts] **************************************
changed: [localhost] => (item=test1)
changed: [localhost] => (item= test2)
TASK [Create a list of host for later reuse. Will be scoped to localhost] **********************
ok: [localhost]
TASK [Store password for later reuse as vars_prompt are limited to play] ***********************
ok: [localhost]
PLAY [Do the actual work] **********************************************************************
TASK [Gathering Facts] *************************************************************************
ok: [test1]
ok: [test2]
TASK [Make sure users are present] *************************************************************
changed: [test2] => (item=user1)
changed: [test1] => (item=user1)
changed: [test2] => (item= user2)
changed: [test1] => (item= user2)
changed: [test2] => (item= user3)
changed: [test1] => (item= user3)
PLAY RECAP *************************************************************************************
localhost : ok=4 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
test1 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
test2 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

ansible ios_command timeout when doing "show conf" on cisco 3850

I've got a simple ansible playbook that works fine on most ios devices. It fails on some of my 3850 switches with what looks like a timeout when doing a "show conf". How do I specify a longer, non-default timeout for command completion with the ios_command module (and presumably also ios_config)?
Useful details:
Playbook:
---
- hosts: ios_devices
gather_facts: no
connection: local
tasks:
- name: OBTAIN LOGIN CREDENTIALS
include_vars: secrets.yaml
- name: DEFINE PROVIDER
set_fact:
provider:
host: "{{ inventory_hostname }}"
username: "{{ creds['username'] }}"
password: "{{ creds['password'] }}"
- name: LIST NAME SERVERS
ios_command:
provider: "{{ provider }}"
commands: "show run | inc name-server"
register: dns_servers
- debug: var=dns_servers.stdout_lines
successful run:
$ ansible-playbook listnameserver.yaml -i inventory/onehost
PLAY [ios_devices] *****************************************************************************************************************
TASK [OBTAIN LOGIN CREDENTIALS] ****************************************************************************************************
ok: [iosdevice1.example.com]
TASK [DEFINE PROVIDER] *************************************************************************************************************
ok: [iosdevice1.example.com]
TASK [LIST NAME SERVERS] ***********************************************************************************************************
ok: [iosdevice1.example.com]
TASK [debug] ***********************************************************************************************************************
ok: [iosdevice1.example.com] => {
"dns_servers.stdout_lines": [
[
"ip name-server 10.1.1.166",
"ip name-server 10.1.1.168"
]
]
}
PLAY RECAP *************************************************************************************************************************
iosdevice1.example.com : ok=4 changed=0 unreachable=0 failed=0
unsuccessful run:
$ ansible-playbook listnameserver.yaml -i inventory/onehost
PLAY [ios_devices] *****************************************************************************************************************
TASK [OBTAIN LOGIN CREDENTIALS] ****************************************************************************************************
ok: [iosdevice2.example.com]
TASK [DEFINE PROVIDER] *************************************************************************************************************
ok: [iosdevice2.example.com]
TASK [LIST NAME SERVERS] ***********************************************************************************************************
fatal: [iosdevice2.example.com]: FAILED! => {"changed": false, "msg": "timeout trying to send command: show run | inc name-server", "rc": 1}
to retry, use: --limit #/home/sample/ansible-playbooks/listnameserver.retry
PLAY RECAP *************************************************************************************************************************
iosdevice2.example.com : ok=2 changed=0 unreachable=0 failed=1
The default timeout is 10 seconds if the request takes longer than this ios_command will fail.
You can add the timeout as a key in the provider variable, like this:
- name: DEFINE PROVIDER
set_fact:
provider:
host: "{{ inventory_hostname }}"
username: "{{ creds['username'] }}"
password: "{{ creds['password'] }}"
timeout: 30
If you've already got a timeout value in provider here's a handy way to update only that key in the variable.
- name: Update existing provider timeout key
set_fact:
provider: "{{ provider | combine( {'timeout': '180'} ) }}"

How to generate single reusable random password with ansible

That is to say: How to evaluate the password lookup only once?
- name: Demo
hosts: localhost
gather_facts: False
vars:
my_pass: "{{ lookup('password', '/dev/null length=15 chars=ascii_letters') }}"
tasks:
- debug:
msg: "{{ my_pass }}"
- debug:
msg: "{{ my_pass }}"
- debug:
msg: "{{ my_pass }}"
each debug statement will print out a different value, e.g:
PLAY [Demo] *************
TASK [debug] ************
ok: [localhost] => {
"msg": "ZfyzacMsqZaYqwW"
}
TASK [debug] ************
ok: [localhost] => {
"msg": "mKcfRedImqxgXnE"
}
TASK [debug] ************
ok: [localhost] => {
"msg": "POpqMQoJWTiDpEW"
}
PLAY RECAP ************
localhost : ok=3 changed=0 unreachable=0 failed=0
ansible 2.3.2.0
Use set_fact to assign permanent fact:
- name: Demo
hosts: localhost
gather_facts: False
vars:
pwd_alias: "{{ lookup('password', '/dev/null length=15 chars=ascii_letters') }}"
tasks:
- set_fact:
my_pass: "{{ pwd_alias }}"
- debug:
msg: "{{ my_pass }}"
- debug:
msg: "{{ my_pass }}"
- debug:
msg: "{{ my_pass }}"
I've been doing it this way and never had an issue.
- name: Demo
hosts: localhost
gather_facts: False
tasks:
- set_fact:
my_pass: "{{ lookup('password', '/dev/null length=15 chars=ascii_letters') }}"
- debug:
msg: "{{ my_pass }}"
The lookup password is nice, but what if you have password specification, like it have to contain specific characters, or must not contain uppercase... the lookup also does not guarantee that the password will have special characters if needed to have...
I have ended with custom jinja filter, that might help somebody ( works fine for me :) )
https://gitlab.privatecloud.sk/vladoportos/custom-jinja-filters
The problem is that you are using the password module wrong, or at least according to the latest documentation (maybe this a new feature on 2.5):
Generates a random plaintext password and stores it in a file at a given filepath.
By definition,the lookup password generates a random password AND stores it on the specified path for subsequent lookups. So, first time it checks if the specified path exists, and if not generates a random password and stores it on that path, subsequent lookups will just retrieve it. Because you are using /dev/null as store path, you are forcing ansible to generate a new random password because everytime it checks for existence it finds nothing.
If you want to have a random password per host + client or whatever
all you need to do to is use some templating and set the store path based on those parameters.
For example:
---
- name: Password test
connection: local
hosts: localhost
tasks:
- name: create a mysql user with a random password
ansible.builtin.debug:
msg: "{{ lookup('password', 'credentials/' + item.host + '/' + item.user + '/mysqlpassword length=15') }}"
with_items:
- user: joe
host: atlanta
- user: jim
host: london
- name: Another task that uses the password of joe
ansible.builtin.debug:
msg: "{{ lookup('password', 'credentials/atlanta/joe/mysqlpassword length=15') }}"
- name: Another task that uses the password of jim
ansible.builtin.debug:
msg: "{{ lookup('password', 'credentials/london/jim/mysqlpassword length=15') }}"
And this is the task execution, as you can see, the three tasks are getting the right generated passwords:
TASK [Gathering Facts] ***********************************************************************************************
ok: [localhost]
TASK [create a mysql user with a random password] ********************************************************************
ok: [localhost] => (item={'user': 'joe', 'host': 'atlanta'}) => {
"msg": "niwPf4tk9HWHhNc"
}
ok: [localhost] => (item={'user': 'jim', 'host': 'london'}) => {
"msg": "dHJdg,OjOEqdyrW"
}
TASK [Another task that uses the password of joe] ********************************************************************
ok: [localhost] => {
"msg": "niwPf4tk9HWHhNc"
}
TASK [Another task that uses the password of jim] ********************************************************************
ok: [localhost] => {
"msg": "dHJdg,OjOEqdyrW"
}
This has the advantage that, even if you play fails and you have to re-execute you will not get the same previous random password,that you can then store on a key-chain or just delete them.

Using lookup plugin to check SHA512 password hash

In my Ansible git repo, I have a var file with contents like this
vault_users:
alex:
password: $6$PwhqORmvn$tXctAkh9RLs60ZFhn9Cxz/eLZEx1UhQkbDIoM6xWsk7M18TApDd9/b8CHJnEiaiQE2YJ8mqu6kvsGuImDt4dy/
danny:
password: $6$PwhqORmvn$tXctAkh9RLs60ZFhn9Cxz/eLZEx1UhQkbDIoM6xWsk7M18TApDd9/b8CHJnEiaiQE2YJ8mqu6kvsGuImDt4dy/
gary:
password: $6$PwhqORmvn$tXctAkh9RLs60ZFhn9Cxz/eLZEx1UhQkbDIoM6xWsk7M18TApDd9/b8CHJnEiaiQE2YJ8mqu6kvsGuImDt4dy/
Now, I want to check if the password hashes from this var file matches the ones from the /etc/shadow file on a remote server. I know it is possible to mix Ansible and a bash/python script to get what I want. I would like to know if it is possible to do this using pure Ansible playbooks only (no bash/python scripts) using the lookup plugin or some other Ansible feature.
You can use line in file to check if line has changed, register result and store it in another variable if lineinfile module returned "changed".
Unfortunately, due to this bug you can't simply use with_items and backrefs in lineinfile module to check if strings are valid, so i used a little include hack.
So we have a playbook called playbook.yml and task called checkpasswords.yml, let's explain each of them.
playbook.yml
- hosts: localhost
tasks:
# execute checkpasswords.yml for each user in vault_users dict
# and pass each user (or item) as {{ user }} variable to included task
- include: checkpasswords.yml user="{{ item }}"
with_items: "{{ vault_users }}"
- debug: msg="{{ changed_users|default([]) }}"
checkpasswords.yml
- name: check for user and hash
lineinfile:
dest: /etc/shadow
regexp: '{{ user }}:([^:]+):(.*)'
# replace sting with user:hashed_password:everything_that_remains
line: '{{ user }}:{{ vault_users[user].password }}:\2'
state: present
backrefs: yes
register: u
- name: changed users
set_fact:
# set changed_users list to [] if not present and add [user] element
# when user password has changed
changed_users: "{{ changed_users|default([]) + [user] }}"
when: u.changed
hashvars.yml
vault_users:
root:
password: "nothing to see here"
my_user:
password: "nothing here"
I included variables to hashvars.yml file and changed hashes for my_user and root inside it. So the result of executing this playbook will be something like output below, don't forget --check!
ansible-playbook playbook.yml -e #hashvars.yml --check
PLAY [localhost] ***************************************************************
TASK [setup] *******************************************************************
ok: [localhost]
TASK [include] *****************************************************************
included: /home/my_user/workspace/so/checkpasswords.yml for localhost
included: /home/my_user/workspace/so/checkpasswords.yml for localhost
TASK [check for user and hash] *************************************************
changed: [localhost]
TASK [changed users] ***********************************************************
ok: [localhost]
TASK [check for user and hash] *************************************************
changed: [localhost]
TASK [changed users] ***********************************************************
ok: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": [
"my_user",
"root"
]
}
PLAY RECAP *********************************************************************
localhost : ok=8 changed=2 unreachable=0 failed=0

Resources