Adding a user during startup of a machine using CloudFormation

Viewed 444

I am trying to create a user using CloudFormation after startup of a Linux machine. I use the following code to do so:

  Metadata:
  AWS::CloudFormation::Init:
    config:
      groups:
        ansible: {}
      users:
        ansible:
          groups:
            - "ansible"
          homeDir: "/home/ansible"
      files:
        /home/ansible/.ssh/authorized_keys:
          content: !Sub |
            '{{ resolve:secretsmanager:
              arn:aws:secretsmanager:eu-central-1:account:secret:secretname:
                SecretString:
                  secretstringpath }}'
          mode: "000644"
          owner: "ansible"
          group: "ansible"
Properties:
  UserData:
    Fn::Base64: !Sub |
      #!/bin/bash -xe
      yum update -y
      yum install -y aws-cfn-bootstrap
      /opt/aws/bin/cfn-init -v \
        --stack ${AWS::StackName} \
        --resource LinuxEC2Instance \
        --region ${AWS::Region}

However, during startup I get the following error message:

[ 96.72999017] cloud-init[2959]: Error occurred during build: Failed to add user ansible

What does this error mean? It does not seem to work as expected the way I do it ...

2 Answers

Before you can assign users to custom groups, you have to create such groups.

For that there is groups option in AWS::CloudFormation::Init.

For example:

groups: 
  ansible: {}

For anyone coming across the Error occurred during build: Failed to add user error mentioned by Benny above, I managed to solve this by creating a second config and creating the users within it:

  Metadata:
  AWS::CloudFormation::Init:
  configSets: 
    ascending: 
      - "config1"
      - "config2"
    descending: 
      - "config2"
      - "config1"
    config1:
      groups:
        ansible: {}
    config2:
      users:
        ansible:
          groups:
            - "ansible"
          homeDir: "/home/ansible"
Related