Assign variable by referencing another - variables

In the following Ansible Playbook, I am trying to create a user's password using predefined variables from defaults/main.yml which in return calls password from vars/passwords.yml. this file will be vaulted later.
vars/passwords
---
passwords:
foobar:
password: pass1234
defaults/main.yml
users:
- username: foobar
group: barfoo
password: "{{passwords.foobar}}"
tasks/main.yml
- include_vars: passwords.yml
- name: Create user
user:
name: "{{item.username}}"
group: "{{item.group}}"
password: "{{item.password | password_hash('sha512') }}"
When I run this playbook, I get the following error:
ERROR:
{
"msg": "[{u'username': u'foobar',
u'group': u'barfoo',
u'password': u'{{passwords.username}}'}]: 'list object' has no attribute 'username'"
}
Any idea how can I achieve assigning a variable by referencing another one.

the first file you provided, has passwords as a list variable, while in your defaults/main.yml file you are expecting a dictionary variable (passwords.foobar).
please change 1st file contents to:
---
passwords:
foobar: pass1234
cant comment about the rest, it looks to me that the tasks/main.yml is missing a line, probably a line including with_items statement. I dont imply its a problem in your code, you just probably didn't paste all your code to this question.

With the current variables files (defaults and vars), the solution for me was to call the password for user bar using the username as a key. I currently have:
- include_vars: passwords.yml
- name: Create user
user:
name: "{{item.username}}"
group: "{{item.group}}"
password: "{{item.password | password_hash('sha512') }}"
the new defaults/main.yml will not have a password key/value:
users:
- username: foobar
group: barfoo
Now with vars/passwords.yml :
---
passwords:
foobar:
password: pass1234
I can edit my change my task to:
- include_vars: passwords.yml
- name: Create user
user:
name: "{{item.username}}"
group: "{{item.group}}"
password: "{{passwords[item.username].password | password_hash('sha512') }}"
This solved my problem, and allows me to vault passwords.yml.
Please let me know if you have any improvements or suggestions.

Related

Ansible uri module loop on files

I'm using the Ansible uri module to make a PUT API call and using all files in a directory as parameters.
I have a list of files in a directory, and I want to use the name and the content of each file in the API call
First of all i tried to list all files.
- name: "Find pipeline files in folder"
find:
paths: "/app/pipelines"
patterns: "pipeline-*.json"
file_type: "file"
register: pipe_files
- debug:
var: pipe_files
Then I want to make a loop on each file in the directory and call the API
- name: PUT PIPE
uri:
method: PUT
headers:
Content-Type: "application/json"
url: "https://api_url/**FILE_NAME**"
user: "user"
password: "user_pass"
body_format: json
body: "{{ lookup('file','/app/pipelines/**FILE_NAME.json**') }}"
validate_certs: no
force_basic_auth: yes
validate_certs: no
return_content: yes
register: pipeline_created
until: pipeline_created.status == 200
When I deploy the content, I don't have the exact filename, how can I make the loop on each file to call the API?
Best regards,
Thanks in advance.
pipe_files is a register from a find task. You can have a look at returned values in the find module documentation. You can also examine your debug task output to better get accustomed with the content of the variable.
Anyway. The list of file objects returned will be in pipe_files.files. Each element is a dict where the information you need is in the path key.
You may test with
- name: PUT pipeline
uri:
method: PUT
headers:
Content-Type: "application/json"
url: "https://api_url/{{ item.path | basename }}" # depends on input list content
user: "user"
password: "user_pass"
body_format: json
body: "{{ lookup('file', item.path) }}" # content
validate_certs: no
force_basic_auth: yes
validate_certs: no
return_content: yes
until: pipeline_created.status == 200
loop: "{{ pipe_files.files }}"
register: pipeline_created # result will become a list

Create Ansible variables for username and password with special characters

I have my vcenter username "Administrator#vsphere.local" and password as "Test#2100$1", if I create variable as below:
vars:
- username: 'vsphere.local\Administrator'
vars_prompt:
- name: password
prompt: Enter Vcenter password to authenticate fence user
It authenticates with wrong username and password, when checked in the configuration it shows:
username = vsphere.localAdministrator {without the slash}
password = Test#2100 {without the $1 characters in the password text}.
Kindly suggest me how to key in the AD domain username "vsphere.local\Administrator" and password with special character as ansible variable.
so a simple test to check the value off user/password:
i have added private: no to see the password typed
- name: test
hosts: localhost
vars:
username: vsphere.local\Administrator
vars_prompt:
- name: password
prompt: Enter Vcenter password to authenticate fence user
private: no
tasks:
- debug:
msg: password for {{ username }} is {{ password}}
result:
ok: [localhost] =>
msg: password for vsphere.local\Administrator is Test#2100$1

How to disable Ansible's password obfuscating feature

I have a simple Ansible playbook to
Fetch a database connection config from an RestAPI,
Extract the config object from the payload,
Using the config JSON (as request body) to create a PUT request to another RestAPI.
At the 3rd stage I found that the database username and password combination is wrong. Later, while I print the outputs, I have found that the password has been replaced with a string named "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER".
After some googling, I found that this is a security feature by Ansible. Unfortunately, I haven't found any configuration or something like this to disable this feature. Is it possible to disable this feature? Or any other workaround?
---
- name: my-playbook
gather_facts: no
hosts: all
vars_files:
- secret
tasks:
- name: Fetch the config payload from the API
uri:
url: "{{get_config}}"
method: GET
user: "{{username}}"
password: "{{password}}"
validate_certs: no
return_content: yes
status_code: 200
body_format: json
register: config
- name: Extract the config object
set_fact:
config_raw: "{{ config.json | json_query(jmesquery) }}"
vars:
jmesquery: '{{name}}.config'
- name: print the config
debug:
msg: "{{config_raw}}"
- name: Creating object using config
uri:
url: "{{create_ocject}}"
method: PUT
user: "{{username}}"
password: "{{password}}"
validate_certs: no
body: "{{config_raw}}"
body_format: json
return_content: yes
status_code: 200
headers:
Content-Type: "application/json"
register: test_res
- name: output value
debug:
msg: "{{test_res.json}}"

Symfony 4 login form with security and database users

I was a total noob on Symfony about a week ago and I thought I should just dive in Symfony 4. After a week of trying to solve the basic login problem, I believe the documentation is still missing some parts.
Now I've found a solution and I will share it along with some tips on what you might be doing wrong. First part of the answer is a list of suggestions, while the second part is the creation of a project with working login from scratch (supposing you already have composer installed and using a server like apache).
Part 1: Suggestions
403 Forbidden
Check the access_control: key in security.yaml. The order of the rules has impact, since no more than one rule will match each time. Keep most specific rules on top.
login_check
Make sure the form action sends you to the login_check path, or whatever you changed it to in security.yaml.
Also check that you have declared a route for the login_check path either in a controller or in routes.yaml.
input name
Symfony forms tend to encapsulate input names in an array, while it only expects them to be named _username and _password (you can change that in security.yaml) to count it as a login attempt. So inspect the inputs to make sure the name attributes are correct.
Part 2: Full Symfony 4 Login
Project Setup
Let's start by creating the project. Open cmd/terminal and go to the folder you want to contain the project folder.
cd .../MyProjects
composer create-project symfony/website-skeleton my-project
cd my-project
Now you have created a Symfony 4 website template in .../MyProjects/my-project and the cmd/terminal is in that path and will execute the rest of the commands properly.
Check in your .../MyProjects/my-project/public folder for a .htaccess file. If it exists you are fine, else run the following command.
composer require symfony/apache-pack
You can now find your site by visiting my-project.dev/public. If you want to remove this public path, you should do so using the .htaccess file, not moving the index.php.
Project Settings
1) Edit the DATABASE_URL key inside the .env file to correspond to your database settings.
2) Edit the config/packages/security.yaml file, so it looks like this:
security:
encoders:
App\Entity\User:
algorithm: bcrypt
providers:
user:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
provider: user
form_login:
#login_path: login
#check_path: login_check
default_target_path: homepage
#username_parameter: _username
#password_parameter: _password
logout:
#path: /logout
#target: /
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: ROLE_USER }
- { path: ^/admin, roles: ROLE_ADMIN }
Some explanation:
App\Entity\User is the User entity you 'll create in a while to handle the login.
The user provider is just a name that needs to have a match in providers and firewalls.
The logout key must be declared if you want to allow the user to... well, logout.
Values in #comment reveal the default value we'll be using later on and act as a reference of what you are more likely to change.
User Entity
A user must have a role, but could have more. So let's build a UserRole Entity first for a ManyToMany relationship.
php bin/console make:entity userRole
All entities start with an id property. Add a role too.
php bin/console make:entity user
User needs the username, password and roles properties, but you can add more.
Let's edit the src/Entity/User.php file:
Add the UserInterface interface to your User class.
use Symfony\Component\Security\Core\User\UserInterface;
class User implements UserInterface
Edit the generated getRoles(), to make it return string array.
public function getRoles(): array
{
$roles = $this->roles->toArray();
foreach($roles as $k => $v) {
$roles[$k] = $v->getRole();
}
return $roles;
}
getSalt() and eraseCredentials() are functions to implement the UserInterface interface.
public function getSalt()
{
return null;
}
public function eraseCredentials()
{
}
Using the bcrypt algorithm (as we set in security.yaml) we don't need a salt. It generates automatically one. No, you don't store this salt anywhere and yes, it will produce different hash for the same password every time. But yes, it will work somehow (magic...).
If you need a different algorithm, that uses salt, you need to add a salt property on the User entity.
Homepage
For testing purposes we will create a homepage
php bin/console make:controller homepage
Edit the generated src/Controller/HomepageController.php file to change the root to /
#Route("/", name="homepage")
Login Controller
php bin/console make:controller login
Edit the generated src/Controller/LoginController.php file to make it like this:
<?php
namespace App\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use App\Form\LoginType;
class LoginController extends Controller
{
/**
* #Route("/login", name="login")
*/
public function index(AuthenticationUtils $authenticationUtils)
{
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
$form = $this->createForm(LoginType::class);
return $this->render('login/index.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'form' => $form->createView(),
]);
}
/**
* #Route("/logout", name="logout")
*/
public function logout() {}
/**
* #Route("/login_check", name="login_check")
*/
public function login_check() {}
}
Login Form
php bin/console make:form login
You don't have to associate it to the User entity.
Edit the generated src/Form/LoginType.php file to add this:
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
replace this:
$builder
->add('_username')
->add('_password', PasswordType::class)
->add('login', SubmitType::class, ['label' => 'Login'])
;
and add this function, to prevent Symfony from changing the input names you requested above by enclosing them in login[...]
public function getBlockPrefix() {}
Login Template
Edit the templates/login/index.html.twig file to add this code in the {% block body %} ... {% endblock %}:
{% if error %}
<div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
{{ form_start(form, {'action': path('login_check'), 'method': 'POST'}) }}
{{ form_widget(form) }}
{{ form_end(form) }}
Database Generation
php bin/console doctrine:migrations:generate
php bin/console doctrine:migrations:migrate
This should have generated your database, according to your User and UserRole entities.
Generate Password
The following command will provide you with a hashed password you can directly insert into the database. The password will be hashed with the algorithm specified in security.yaml.
php bin/console security:encode-password my-password
Hope this helps!
Thank you very much, the documentation lacks some important things, but this works very good. For others, check the order of the access-control entries, because one misplaced entry may block the whole process.
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin, roles: ROLE_ADMIN }
This was working, but this not
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin, roles: ROLE_ADMIN }
- { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }

Symfony 4 one entity, two entity Manager

Hello everyone, I'm trying to have 2 entityManagers for one entity in Symfony4 but I have some trouble to do this.
When I persist an entity it works,(For example if have two entity Mananagers : Customer and Default ,when I use Customer or Default to persist) but when I want to use Repository, The first entity Managare in doctrine.yaml is always used.
I have to do this because I have 2 databases. One in internet and one inside my intranet that i have created and I search to do is that when the user click one button for example. It update the database on internet.
config/packages/doctrine.yaml
doctrine:
dbal:
default_connection: default
connections:
default:
driver: pdo_mysql
host: **************
port: 3306
dbname: intranetDb
user: **********
password: *****
charset: UTF8
customer:
driver: pdo_mysql
host: internetDb
port: 3306
dbname: *********
user: *********
password: *********
charset: UTF8
orm:
default_entity_manager: default
entity_managers:
default:
connection: default
auto_mapping: false
mappings:
Main:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: Main
customer:
connection: customer
auto_mapping: false
mappings:
Customer:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: Main
MyController.php
..
$drug = $this->getDoctrine()->getRepository(Drug::class,'customer')->findAll() ;
..
This code always give me the data inside of default and if I put customer first inside of orm the customer is always given.
Some help will be welcome because I have this problem in few days and I have no Idea to solve this(It's probably because of symfony version that I didn't found solution inside forum).
Thank you.(And sorry for my bad English)
You can get the repository from an entity manager, instead of getting it from the ManagerRegistry returned by getDoctrine().
Example:
[...]
$this->getDoctrine()->getManager('manager_name')->getRepository('class_name');
[...]