I need to copy the content of a cert file which comes from the secretsmanager into an EC2 instance on startup using CloudFormation.
Edit:
I added an IAM Role, a Policy, and an InstanceProfile in my code to ensure that I can access the SecretsManager value using UserData
The code looks like this now:
SecretsManagerAccessRole:
Type: AWS::IAM::Role
Properties:
RoleName: CloudFormationSecretsManagerAccessRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
AWS: !Sub arn:aws:iam::${AWS::AccountId}:root
Action: sts:AssumeRole
Path: "/"
SecretsManagerInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Path: "/"
Roles: [ !Ref SecretsManagerAccessRole ]
SecretsManagerInstancePolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: SecretsManagerAccessPolicy,
PolicyDocument:
Statement:
- Effect: Allow
Action: secretsmanager:GetSecretValue
Resource: <arn-of-the-secret>
Roles: [ !Ref SecretsManagerAccessRole ]
LinuxEC2Instance:
Type: AWS::EC2::Instance
Properties:
IamInstanceProfile: !Ref SecretsManagerInstanceProfile
UserData:
Fn::Base64: !Sub |
#!/bin/bash -xe
yum update -y
groupadd -g 110 ansible
adduser ansible -g ansible
mkdir -p /home/ansible/.ssh
chmod 700 /home/ansible/.ssh
aws secretsmanager get-secret-value \
--secret-id <arn-of-the-secret> \
--region ${AWS::Region} \
--query 'SecretString' \
--output text > /home/ansible/.ssh/authorized_keys
chmod 000644 /home/ansible/.ssh/authorized_keys
chown -R ansible.ansible /home/ansible/.ssh/
cat /home/ansible/.ssh/authorized_keys
During startup of the instance, I get this issue here:
Unable to locate credentials. You can configure credentials by running "aws configure".
It seems like the user did not get the necessary role to perform this action in UserData? Why is that?
{{ resolve:secretsmanager->{{resolve:secretsmanager. - lexicore