Cannot create user because the group does not exits on ansible

Viewed 32

I am running this playbook to install mysql.

File var.yml:

PORT : 3306
USER : mysql
USERID : "{{ PORT }}"
GROUP : mysql
GROUPID : "{{ PORT }}"
SECGROUP : wls
DBUSER : root
DBPASSWD : "{{ DBPASS }}"

GROUPS:
  - name: "{{ GROUP }}"
    gid: "{{ GROUPID }}"

USERS:
  - name : "{{ USER }}"
    uid: "{{ USERID }}"
    group: "{{ GROUP }}"
    groups: "{{ SECGROUP }}"
    comment: "{{ USER }}"

playbook.yml:

tasks:
 - name: 1. create group
   group:
    name: "{{ item.name }}"
    gid: "{{ item.gid }}"
    state: present
   with_items:
     - "{{ GROUPS }}"

 - name: 2. create user account
   user:
    name: "{{ item.name }}"
    group: "{{ item.group }}"
    groups: "{{ item.groups }}"
    uid: "{{ item.uid }}"
    comment: "{{ item.comment }}"
   with_items:
     - "{{ USERS }}"

When I run it, I have an issue with the second task:

failed : (item={u'comment': u'mysql', u'group': u'mysql', u'name': u'mysql', u'groups': u'wls', u'uid': u'3306'}) => {"ansible_loop_var": "item", "changed": false, "item": {"comment}: "mysql", "group": "mysql", "groups" : "wls", "name": "mysql", "uid": "3306"}, "msg": "Group wls does not exist"}

How can I fix it?

1 Answers

It's because group wls does not exist as error says: "msg": "Group wls does not exist"

You cannot create an user with a non-existent group in its groups. You either need to remove group wls from USERS[0].groups or create group wls. Your task 1. only creates group mysql.

To create both groups in task 1. You can just add group wls to the list:

GROUPS:
  - name: "{{ GROUP }}"
    gid: "{{ GROUPID }}"
  - name: "{{ SECGROUP }}"
    gid: "<provide gid here>"

(Note: normally in Ansible you don't have to provide gid to group action and it would chose one, but the way you have written your task 1 requires it).

This will make your task 1 create both mysql and wls groups and also pass task 2.

Related